Fix PSBT input classification and finalization
What changed, and why it matters
This commit fixes bugs in how the COLDCARD hardware wallet classifies and finalizes Bitcoin transaction inputs from PSBT files. Before the fix, the device could incorrectly treat foreign or already-signed inputs as complete, producing an invalid ready-to-broadcast transaction instead of returning a still-partial PSBT. The patch separates input analysis from key selection, validates scripts against known wallets before finalizing, and refuses to finalize inputs whose signatures or scripts cannot be verified. The changelog explicitly calls these security-relevant bugfixes and credits an external reporter.
Treat this as a security fix and ensure affected firmware versions are upgraded. Wallets or services that build PSBTs for COLDCARD should verify that partially signed PSBTs are returned when any input cannot be safely finalized, and should not rely on previous firmware behavior that could emit invalid finalized transactions.
Security signals we found
Changelog labels the changes as 'Bugfix' and credits 'Nabeel-javed' for one of them
Separation of input classification from signing-key selection reduces risk of misclassifying foreign/presigned inputs
New script_validated flag prevents finalization of inputs whose scripts/signatures were not verified
Multisig finalization now checks signature membership against the validated script's pubkey order and threshold
Presigned inputs from another wallet are no longer finalized using the active wallet
Foreign single-sig inputs must have a signature that matches the committed pubkey/hash
Tests assert that malformed or unverifiable inputs cause 'PSBT output failed' instead of producing a broadcastable transaction
Evidence from the diff
The change refactors shared/psbt.py so that input classification (analyze_input) happens independently of signing-key selection (determine_my_signing_key). It adds a script_validated flag, requires redeem/witness scripts to match the UTXO scriptPubKey, and only finalizes multisig inputs when the script has been validated against the active wallet and enough signatures belong to that script’s pubkeys. Finalization now returns a signed PSBT rather than an invalid transaction when some inputs cannot be finalized. New tests cover foreign multisig inputs, mismatched thresholds, wrong pubkeys, bad redeem scripts, missing witness scripts, and mixed foreign/own inputs.
Changed components
shared/psbt.pytesting/test_multisig.pytesting/test_sign.pyreleases/ChangeLog.mdInspect captured patch +851 / −153
### releases/ChangeLog.md
@@ -34,6 +34,8 @@ This lists the changes in the most recent firmware, for each hardware platform.
- Bugfix: Harden PSBTv2 parsing by rejecting key data on singleton fields,
malformed global input/output count encodings, and files missing the required
global version.
+- Bugfix: Correct finalization of presigned segwit inputs. Thanks to Nabeel-javed.
+- Bugfix: Return a signed PSBT instead of an invalid transaction when some inputs cannot be finalized.
# Mk Specific Changes
### shared/psbt.py
@@ -11,7 +11,7 @@
from uhashlib import sha256
from uio import BytesIO
from sffile import SizerFile
-from multisig import MultisigWallet, disassemble_multisig_mn
+from multisig import MultisigWallet, disassemble_multisig_mn, disassemble_multisig
from exceptions import FatalPSBTIssue, FraudulentChangeOutput
from serializations import ser_compact_size, deser_compact_size, hash160
from serializations import CTransaction, CTxIn, CTxInWitness, CTxOut, ser_string, COutPoint
@@ -600,7 +600,8 @@ class psbtInputProxy(psbtProxy):
blank_flds = (
'unknown', 'utxo', 'witness_utxo', 'sighash', 'redeem_script', 'witness_script',
- 'fully_signed', 'is_segwit', 'is_multisig', 'is_p2sh', 'num_our_keys',
+ 'fully_signed', 'script_validated', 'is_segwit', 'is_multisig',
+ 'is_p2sh', 'num_our_keys',
'required_key', 'scriptSig', 'amount', 'scriptCode', 'previous_txid',
'prevout_idx', 'sequence', 'req_time', 'req_height', 'addr_fmt',
'wif_redeem_script',
@@ -786,15 +787,29 @@ def witness_utxo_is_provably_segwit(self, utxo):
return (is_wrapped_p2wpkh_redeem(redeem_script) or is_wrapped_p2wsh_redeem(redeem_script)) \
and hash160(redeem_script) == addr_or_pubkey
- def determine_my_signing_key(self, my_idx, utxo, my_xfp, psbt, cosign_xfp=None):
- # See what it takes to sign this particular input
- # - type of script
- # - which pubkey needed
- # - scriptSig value
- # - also validates redeem_script when present
+ def redeem_or_witness_script(self):
+ # the script a p2sh/p2wsh input actually spends, as bytes
+ # - only meaningful once analyze_input() has run the WIF-store match,
+ # which is what sets wif_redeem_script when the PSBT omits the script
+ if self.wif_redeem_script:
+ return self.wif_redeem_script
+ ks = self.witness_script or self.redeem_script
+ return self.get(ks) if ks else None
+
+ def analyze_input(self, utxo, psbt):
+ # Work out what is being spent here, from the UTXO and the scripts provided.
+ # - runs for every input, including those we will not be signing, because
+ # finalization needs to know the script type to place signatures
+ # - scripts we cannot make sense of are classified as such, not raised over:
+ # they simply cannot be finalized, and determine_my_signing_key()
+ # complains if the input is ours (a WIF-store redeem script conflict
+ # on our own input still asserts)
+ # - returns the pubkey/hash the scriptPubKey commits to, and our subpaths
self.amount = utxo.nValue
- self.addr_fmt, addr_or_pubkey, addr_is_segwit = utxo.get_address()
+ self.addr_fmt, addr_or_pubkey, self.is_segwit = utxo.get_address()
+ self.is_multisig = False
+ self.is_p2sh = False
subpaths = dict(self.subpaths or {}) # shallow copy
@@ -812,90 +827,145 @@ def determine_my_signing_key(self, my_idx, utxo, my_xfp, psbt, cosign_xfp=None):
if self.redeem_script:
assert self.get(self.redeem_script) == self.wif_redeem_script
- if not subpaths or self.fully_signed or (not self.num_our_keys):
- # without xfp+path we will not be able to sign this input
- # - okay if fully signed
- # - okay if payjoin or other multi-signer (not multisig) txn
- self.required_key = None
- return
-
- self.is_multisig = False
- self.is_p2sh = False
- which_key = None
-
- if self.addr_fmt == OP_RETURN:
- self.required_key = None
- return
- if self.addr_fmt == AF_P2TR:
- raise FatalPSBTIssue("Install EDGE firmware to spend taproot.")
- if self.addr_fmt is None:
- # If this is reached, we do not understand the output well
- # enough to allow the user to authorize the spend, so fail hard.
- raise FatalPSBTIssue('Unhandled scriptPubKey: ' + b2a_hex(addr_or_pubkey).decode())
-
- if addr_is_segwit and not self.is_segwit:
- self.is_segwit = True
-
if self.addr_fmt in [AF_P2SH, AF_P2WSH]:
- # multisig input
+ # multisig input, or single-sig segwit wrapped in p2sh
self.is_p2sh = True
- # we must have the redeem script already (else fail)
- if self.wif_redeem_script:
- redeem_script = self.wif_redeem_script
- else:
- ks = self.witness_script or self.redeem_script
- if not ks:
- raise FatalPSBTIssue("Missing redeem/witness script for input #%d" % my_idx)
-
- redeem_script = self.get(ks)
+ redeem_script = self.redeem_or_witness_script()
+ if not redeem_script:
+ # nothing to tell us what this script is
+ return addr_or_pubkey, subpaths
if self.addr_fmt == AF_P2SH and self.witness_script:
expect = b'\x00\x20' + ngu.hash.sha256s(self.get(self.witness_script))
if not self.redeem_script or self.get(self.redeem_script) != expect:
# redeem script is the only proof the UTXO is really segwit;
# without it the input amount (and fee) cannot be verified
- raise FatalPSBTIssue('Missing/bad redeem script for input #%d' % my_idx)
+ return addr_or_pubkey, subpaths
- self.scriptSig = redeem_script
-
- if not addr_is_segwit and is_wrapped_p2wpkh_redeem(redeem_script):
+ if not self.is_segwit and is_wrapped_p2wpkh_redeem(redeem_script) \
+ and hash160(redeem_script) == addr_or_pubkey:
# segwit p2pkh wrapped in p2sh: exactly one key, not multisig.
# psbt creator tells us the key by providing exactly one subpath.
self.addr_fmt = AF_P2WPKH_P2SH
- addr = redeem_script[2:22]
self.is_segwit = True
-
- assert len(subpaths) == 1, "p2sh-p2wpkh needs one key"
- which_key, = subpaths.keys()
+ addr_or_pubkey = redeem_script[2:22]
else:
self.is_multisig = True
- which_key = set()
- for pubkey, path in subpaths.items():
- if self.part_sigs and (pubkey in self.part_sigs):
- # pubkey has already signed, so ignore
- continue
-
- if path[0] in (my_xfp, cosign_xfp):
- # slight chance of dup xfps, so handle
- which_key.add(pubkey)
-
- elif pubkey in psbt.wif_store:
- which_key.add(pubkey)
-
if self.witness_script and not self.is_segwit and self.is_multisig:
# bugfix
self.addr_fmt = AF_P2WSH_P2SH
self.is_segwit = True
+ if self.addr_fmt in [AF_CLASSIC, AF_BARE_PK, AF_P2WPKH, AF_P2WPKH_P2SH] \
+ and len(self.part_sigs) == 1:
+ # signature supplied by someone else: it can only be finalized if the
+ # key it claims is the one this script commits to. Key origins and
+ # signature counts are not proof of anything.
+ pubkey, = self.part_sigs
+ target = pubkey if self.addr_fmt == AF_BARE_PK else hash160(pubkey)
+ if target == addr_or_pubkey and not (self.is_segwit and (
+ len(pubkey) != 33 or pubkey[0] not in (2, 3))):
+ # v0 witness programs only ever commit to compressed keys
+ self.script_validated = True
+
+ return addr_or_pubkey, subpaths
+
+ def validate_multisig_script(self, my_idx, psbt, utxo, subpaths, M, N):
+ # Find the wallet this multisig input belongs to (or check consistency
+ # with the wallet already selected), and prove the script matches both
+ # the wallet and the UTXO being spent.
+ xfp_paths = list(subpaths.values())
+ xfp_paths.sort()
+
+ try:
+ # only search wallets with correct script type (aka address format)
+ if not psbt.active_multisig:
+ # search for multisig wallet
+ wal = MultisigWallet.find_match(M, N, xfp_paths, [self.addr_fmt])
+ if not wal:
+ raise FatalPSBTIssue('Unknown multisig wallet')
+ else:
+ # check consistent w/ already selected wallet
+ wal = psbt.active_multisig
+ wal.assert_matching(M, N, xfp_paths, self.addr_fmt)
+
+ # validate redeem script, by disassembling it and checking all pubkeys
+ wal.validate_script(self.scriptSig, subpaths=subpaths)
+ target_spk, _ = chains.current_chain().script_pubkey(self.addr_fmt,
+ script=self.scriptSig)
+ assert target_spk == utxo.scriptPubKey, "spk mismatch"
+ psbt.active_multisig = wal
+ except FatalPSBTIssue:
+ raise
+ except BaseException as exc:
+ # sys.print_exception(exc)
+ raise FatalPSBTIssue('Input #%d: %s' % (my_idx, exc))
+
+ def determine_my_signing_key(self, my_idx, utxo, addr_or_pubkey, subpaths, my_xfp,
+ psbt, cosign_xfp=None):
+ # See what it takes to sign this particular input
+ # - which pubkey needed
+ # - scriptCode value
+ # - also finds appropriate multisig wallet to be used
+ # - analyze_input() has already worked out the type of script
+
+ # required_key is left unset (reads as None) for anything we do not sign
+ if not self.num_our_keys:
+ # without a key of ours we will not be able to sign this input
+ # - okay if fully signed
+ # - okay if payjoin or other multi-signer (not multisig) txn
+ # - num_our_keys is unset unless subpaths holds a key of ours
+ return
+ if self.fully_signed:
+ # nothing to sign; singlesig finalization eligibility was checked
+ # in analyze_input(). Multisig validation runs after signing inputs
+ # have selected their wallet.
+ return
+
+ which_key = None
+
+ if self.addr_fmt == OP_RETURN:
+ return
+ if self.addr_fmt == AF_P2TR:
+ raise FatalPSBTIssue("Install EDGE firmware to spend taproot.")
+ if self.addr_fmt is None:
+ # If this is reached, we do not understand the output well
+ # enough to allow the user to authorize the spend, so fail hard.
+ raise FatalPSBTIssue('Unhandled scriptPubKey: ' + b2a_hex(addr_or_pubkey).decode())
+
+ if self.is_p2sh and not (self.is_multisig or self.addr_fmt == AF_P2WPKH_P2SH):
+ # analyze_input() could not work out what this script is
+ if not (self.witness_script or self.redeem_script):
+ raise FatalPSBTIssue("Missing redeem/witness script for input #%d" % my_idx)
+ raise FatalPSBTIssue('Missing/bad redeem script for input #%d' % my_idx)
+
+ # the subscript that legacy sighashing signs over
+ self.scriptSig = self.redeem_or_witness_script() if self.is_p2sh else utxo.scriptPubKey
+
+ if self.is_multisig:
+ which_key = set()
+ for pubkey, path in subpaths.items():
+ if self.part_sigs and (pubkey in self.part_sigs):
+ # pubkey has already signed, so ignore
+ continue
+
+ if path[0] in (my_xfp, cosign_xfp):
+ # slight chance of dup xfps, so handle
+ which_key.add(pubkey)
+
+ elif pubkey in psbt.wif_store:
+ which_key.add(pubkey)
+
+ elif self.addr_fmt == AF_P2WPKH_P2SH:
+ assert len(subpaths) == 1, "p2sh-p2wpkh needs one key"
+ which_key, = subpaths.keys()
+
elif self.addr_fmt in [AF_CLASSIC, AF_P2WPKH]:
# input is hash160 of a single public key
- self.scriptSig = utxo.scriptPubKey
- addr = addr_or_pubkey
-
for pubkey in subpaths:
- if hash160(pubkey) == addr:
+ if hash160(pubkey) == addr_or_pubkey:
which_key = pubkey
break
else:
@@ -904,7 +974,6 @@ def determine_my_signing_key(self, my_idx, utxo, my_xfp, psbt, cosign_xfp=None):
elif self.addr_fmt == AF_BARE_PK:
# input is single public key (less common)
- self.scriptSig = utxo.scriptPubKey
assert len(addr_or_pubkey) in (33, 65) # compressed or uncompressed
if addr_or_pubkey in subpaths:
@@ -915,52 +984,34 @@ def determine_my_signing_key(self, my_idx, utxo, my_xfp, psbt, cosign_xfp=None):
else:
# we don't know how to "solve" this type of input
- pass
+ return
if self.is_multisig:
- # We will be signing this input, so
+ # We will be signing this input, so
# - find which wallet it is or
# - check it's the right M/N to match redeem script
# - which_key can be empty set, meaning all is already signed
- #print("redeem: %s" % b2a_hex(redeem_script))
- M, N = disassemble_multisig_mn(redeem_script)
+ #print("redeem: %s" % b2a_hex(self.scriptSig))
+ try:
+ M, N = disassemble_multisig_mn(self.scriptSig)
+ except AssertionError:
+ raise FatalPSBTIssue('Input #%d: not a multisig script' % my_idx)
if len(self.part_sigs) >= M:
+ # enough signatures already: validate after signing inputs select the wallet
self.fully_signed = True
return
- xfp_paths = list(subpaths.values())
- xfp_paths.sort()
-
- # only search wallets with correct script type (aka address format)
- if not psbt.active_multisig:
- # search for multisig wallet
- wal = MultisigWallet.find_match(M, N, xfp_paths, [self.addr_fmt])
- if not wal:
- raise FatalPSBTIssue('Unknown multisig wallet')
-
- psbt.active_multisig = wal
- else:
- # check consistent w/ already selected wallet
- psbt.active_multisig.assert_matching(M, N, xfp_paths, self.addr_fmt)
-
- # validate redeem script, by disassembling it and checking all pubkeys
- try:
- psbt.active_multisig.validate_script(redeem_script, subpaths=subpaths)
- target_spk, _ = chains.current_chain().script_pubkey(self.addr_fmt,
- script=redeem_script)
- assert target_spk == utxo.scriptPubKey, "spk mismatch"
- except BaseException as exc:
- # sys.print_exception(exc)
- raise FatalPSBTIssue('Input #%d: %s' % (my_idx, exc))
+ self.validate_multisig_script(my_idx, psbt, utxo, subpaths, M, N)
if not which_key and DEBUG:
print("no key: input #%d: type=%s segwit=%d a_or_pk=%s scriptPubKey=%s" % (
my_idx, chains.addr_fmt_str(self.addr_fmt), self.is_segwit or 0,
b2a_hex(addr_or_pubkey), b2a_hex(utxo.scriptPubKey)))
self.required_key = which_key
+ self.script_validated = True
if self.is_segwit:
if self.addr_fmt in [AF_P2WPKH, AF_P2WPKH_P2SH]:
@@ -973,7 +1024,7 @@ def determine_my_signing_key(self, my_idx, utxo, my_xfp, psbt, cosign_xfp=None):
# Also need this scriptCode for native segwit p2pkh
#
assert not self.is_multisig
- self.scriptCode = b'\x19\x76\xa9\x14' + addr + b'\x88\xac'
+ self.scriptCode = b'\x19\x76\xa9\x14' + addr_or_pubkey + b'\x88\xac'
elif not self.scriptCode:
# Segwit P2SH. We need the witness script to be provided.
if not self.witness_script:
@@ -1944,11 +1995,13 @@ def consider_inputs(self, cosign_xfp=None):
if not inp.utxo and not inp.witness_utxo_is_provably_segwit(utxo):
unverified_witness_utxo.append(i)
- # Look at what kind of input this will be, and therefore what
- # type of signing will be required, and which key we need.
+ # Work out what kind of input this is, for every input, and then
+ # what signing will take and which key we need, for ours.
# - also validates redeem_script when present
# - also finds appropriate multisig wallet to be used
- inp.determine_my_signing_key(i, utxo, self.my_xfp, self, cosign_xfp)
+ addr_or_pubkey, subpaths = inp.analyze_input(utxo, self)
+ inp.determine_my_signing_key(i, utxo, addr_or_pubkey, subpaths,
+ self.my_xfp, self, cosign_xfp)
if self.por322 and i and not inp.required_key:
# every POR input past to_spend must be one we will actually sign;
@@ -1990,6 +2043,26 @@ def consider_inputs(self, cosign_xfp=None):
del utxo
+ # Presigned inputs may only validate against an already selected wallet.
+ # Unsupported scripts stay unfinalizable without preventing PSBT signing.
+ if self.presigned_inputs and self.active_multisig:
+ for i, txi in self.input_iter():
+ inp = self.inputs[i]
+ if i not in self.presigned_inputs or not inp.is_multisig or not inp.num_our_keys:
+ continue
+ # Segwit multisig finalization requires the witness-script field.
+ if inp.is_segwit and not inp.witness_script:
+ continue
+ inp.scriptSig = inp.redeem_or_witness_script()
+ try:
+ M, N = disassemble_multisig_mn(inp.scriptSig)
+ inp.validate_multisig_script(i, self, inp.get_utxo(txi.prevout.n),
+ inp.subpaths, M, N)
+ inp.script_validated = True
+ except (AssertionError, FatalPSBTIssue):
+ # malformed scripts or another wallet: leave finalization to the host
+ pass
+
# XXX scan witness data provided, and consider those ins signed if not multisig?
if foreign_por:
@@ -2531,66 +2604,53 @@ def make_txn_segwit_sighash(self, replace_idx, replacement, amount, scriptCode,
return ngu.hash.sha256s(rv.digest())
def multi_input_complete(self, inp):
- # raises if input is not multisig or no active_multisig loaded
+ # raises if input is not multisig
assert inp.is_multisig
- if (len(inp.added_sigs) + len(inp.part_sigs)) >= self.active_multisig.M:
- return True
+ if not inp.script_validated or not self.active_multisig:
+ # script was never checked against a wallet we know, so our
+ # threshold says nothing about this input
+ return False
+ return len(self.multisig_signatures(inp)) == self.active_multisig.M
def is_complete(self):
# Are all the inputs (now) signed?
+ # - exactly what finalize() needs, asked once per input
- # some might have been given as signed
- signed = len(self.presigned_inputs)
-
- # plus we added some signatures
for inp in self.inputs:
- if inp.is_multisig and self.active_multisig:
- if self.multi_input_complete(inp):
- signed += 1
+ if inp.is_multisig:
+ if not self.multi_input_complete(inp):
+ return False
- elif inp.added_sigs:
- signed += 1
+ elif not self.singlesig_signature(inp):
+ return False
- return signed == self.num_inputs
+ return True
def multisig_signatures(self, inp):
assert self.active_multisig
+ M, N, pubkeys = disassemble_multisig(inp.redeem_or_witness_script())
# collect all signatures into one place
# both we added & those already in part_sigs
all_sigs = {}
all_sigs.update(inp.added_sigs)
for pk, get_data in inp.part_sigs.items():
all_sigs[pk] = self.get(get_data)
- if self.active_multisig.bip67:
- # BIP-67 easy just sort by public keys
- sigs = [sig for pk, sig in sorted(all_sigs.items())]
- else:
- # need to respect the order of keys in actual descriptor
- sigs = []
- for xfp, _, _ in self.active_multisig.xpubs:
- for pk, pth in inp.subpaths.items():
- # if xfp matches but pk not in all_sigs -> signer haven't signed
- # it is ok in threshold multisig - just skip
- if (xfp == pth[0]) and (pk in all_sigs):
- sigs.append(all_sigs[pk])
- break
-
- # save space and only provide necessary amount of signatures (smaller tx, less fees)
- sigs = sigs[:self.active_multisig.M]
- return sigs
+ # Ignore unrelated keys and preserve the validated script's key order.
+ return [all_sigs[pk] for pk in pubkeys if pk in all_sigs][:M]
def singlesig_signature(self, inp):
- # return signature that we added
- # or one signature from partial sigs if input is fully sign
- # (i.e. len(part_sigs)>=len(subpaths))
+ # return signature that we added, or the one supplied for an input
+ # whose script analyze_input() matched to the signing key
+ if not inp.script_validated:
+ return None
+
ssig = None
if inp.added_sigs:
# we have added signature to this single sig input
assert len(inp.added_sigs) == 1
ssig = list(inp.added_sigs.items())[0]
- elif inp.part_sigs and inp.fully_signed:
- assert len(inp.part_sigs) == 1
+ elif len(inp.part_sigs) == 1:
rv = list(inp.part_sigs.items())[0]
ssig = rv[0], self.get(rv[1])
@@ -2653,7 +2713,7 @@ def finalize(self, fd):
elif inp.is_p2sh:
# singlesig (p2sh) segwit still requires the script here.
- txi.scriptSig = ser_string(inp.scriptSig)
+ txi.scriptSig = ser_string(inp.redeem_or_witness_script())
else:
# major win for segwit (p2pkh): no redeem script bloat anymore
txi.scriptSig = b''
### testing/test_multisig.py
@@ -4674,4 +4674,323 @@ def hack(psbt):
assert "completely signed already" in story
press_cancel()
+
+
+@pytest.mark.parametrize('addr_fmt', [AF_P2SH, AF_P2WSH, AF_P2WSH_P2SH])
+@pytest.mark.parametrize('M,N', [(1, 1), (1, 2), (2, 3)])
+@pytest.mark.parametrize('include_paths', [True, False, 'claimed_ours'])
+def test_foreign_multisig_not_finalized(addr_fmt, M, N, include_paths, make_multisig,
+ fake_ms_txn, fake_txn, try_sign, try_sign_microsd,
+ clear_ms):
+ clear_ms()
+ # Remove Coldcard's key; the remaining wallet is entirely foreign.
+ keys = make_multisig(M, N + 1)[:-1]
+ foreign = BasicPSBT().parse(fake_ms_txn(1, 1, M, keys, inp_af=addr_fmt,
+ psbt_v2=True)).inputs[0]
+ # Signature contents are irrelevant: unsupported finalization must be rejected.
+ foreign.part_sigs = {pk: b'\x30' + bytes(70)
+ for pk in list(foreign.bip32_paths)[:M]}
+ if not include_paths:
+ foreign.bip32_paths.clear()
+ elif include_paths == 'claimed_ours':
+ foreign.bip32_paths = {pk: struct.pack('<I', simulator_fixed_xfp) + path[4:]
+ for pk, path in foreign.bip32_paths.items()}
+
+ psbt = BasicPSBT().parse(fake_txn(2, 1, segwit_in=True, psbt_v2=True))
+ psbt.inputs[0] = foreign
+ raw = psbt.as_bytes()
+
+ _, signed = try_sign(raw)
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == foreign
+ assert signed.inputs[1].part_sigs
+
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+
+ # Automatic microSD finalization must leave this as a partially signed PSBT.
+ _, signed, txid = try_sign_microsd(raw, finalize=False)
+ assert txid is None
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == foreign
+ assert signed.inputs[1].part_sigs
+
+
+@pytest.mark.parametrize('problem', ['foreign_threshold', 'presigned_count'])
+def test_multisig_incomplete_inputs(problem, clear_ms, import_ms_wallet, make_multisig,
+ fake_ms_txn, try_sign, try_sign_microsd):
+ clear_ms()
+ N = 3 if problem == 'foreign_threshold' else 2
+ keys = import_ms_wallet(2, N, addr_fmt='p2sh-p2wsh', accept=True)
+ psbt = BasicPSBT().parse(fake_ms_txn(3, 1, 2, keys, inp_af=AF_P2WSH_P2SH,
+ psbt_v2=True))
+ sig = b'\x30' + bytes(70)
+ for inp in psbt.inputs[1:]:
+ pk = next(pk for pk, path in inp.bip32_paths.items()
+ if path[:4] != struct.pack('<I', simulator_fixed_xfp))
+ inp.part_sigs[pk] = sig
+
+ if problem == 'foreign_threshold':
+ # Two signatures must not satisfy a foreign 3-of-4 via our active 2-of-3 wallet.
+ foreign_keys = make_multisig(3, 5)[:-1]
+ psbt.inputs[0] = BasicPSBT().parse(fake_ms_txn(1, 1, 3, foreign_keys,
+ inp_af=AF_P2WSH_P2SH, psbt_v2=True)).inputs[0]
+ inp = psbt.inputs[0]
+ inp.part_sigs = {pk: sig for pk in list(inp.bip32_paths)[:2]}
+ inp.bip32_paths.clear()
+ else:
+ # Input 0 is presigned, input 1 completes here, input 2 still needs a cosigner.
+ inp = psbt.inputs[0]
+ inp.part_sigs = {pk: sig for pk in inp.bip32_paths}
+ psbt.inputs[2].part_sigs.clear()
+
+ raw = psbt.as_bytes()
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == psbt.inputs[0]
+ assert len(signed.inputs[1].part_sigs) == 2
+ assert len(signed.inputs[2].part_sigs) == (2 if problem == 'foreign_threshold' else 1)
+
+
+@pytest.mark.parametrize('all_signed', [False, True])
+@pytest.mark.parametrize('addr_fmt', [AF_P2WSH, AF_P2WSH_P2SH])
+def test_finalize_presigned_own_multisig(all_signed, addr_fmt, clear_ms, import_ms_wallet,
+ fake_ms_txn, try_sign, try_sign_microsd):
+ # input0 arrives completely signed by the other cosigners of our own
+ # registered wallet, input1 is completed here: both must finalize, even
+ # though we add no signature of our own to input0
+ clear_ms()
+ keys = import_ms_wallet(2, 3, addr_fmt=addr_fmt, accept=True)
+ psbt = BasicPSBT().parse(fake_ms_txn(2, 1, 2, keys, inp_af=addr_fmt,
+ psbt_v2=True))
+ sig = b'\x30' + bytes(70)
+ our_xfp = struct.pack('<I', simulator_fixed_xfp)
+
+ foreign0 = [pk for pk, path in psbt.inputs[0].bip32_paths.items()
+ if path[:4] != our_xfp]
+ psbt.inputs[0].part_sigs = {pk: sig for pk in foreign0}
+ if all_signed:
+ # all three pubkeys carry a signature (one is ours from an earlier pass)
+ # -> input is fully_signed already at parse time
+ our0 = next(pk for pk in psbt.inputs[0].bip32_paths if pk not in foreign0)
+ psbt.inputs[0].part_sigs[our0] = sig
+
+ fk1 = next(pk for pk, path in psbt.inputs[1].bip32_paths.items()
+ if path[:4] != our_xfp)
+ psbt.inputs[1].part_sigs = {fk1: sig}
+
+ raw = psbt.as_bytes()
+ _, txn = try_sign(raw, finalize=True)
+ tx = CTransaction()
+ tx.deserialize(BytesIO(txn))
+ for i, inp in enumerate(psbt.inputs):
+ redeem = inp.redeem_script
+ assert tx.vin[i].scriptSig == (bytes([len(redeem)]) + redeem if redeem else b'')
+ stack = tx.wit.vtxinwit[i].scriptWitness.stack
+ assert stack[0] == b''
+ assert stack[-1] == inp.witness_script
+ assert len(stack) == 1 + 2 + 1 # dummy + M sigs + witness script
+
+ # microSD flow must finalize automatically too
+ _, txn_sd, txid = try_sign_microsd(raw, finalize=True)
+ assert txid is not None
+ assert txn_sd == txn
+
+
+@pytest.mark.parametrize('bip67', [True, False])
+@pytest.mark.parametrize('problem', ['extra_key', 'wrong_key'])
+def test_multisig_signature_membership(problem, bip67, clear_ms, import_ms_wallet,
+ fake_ms_txn, try_sign, try_sign_microsd):
+ clear_ms()
+ keys = import_ms_wallet(2, 3, addr_fmt='p2wsh', accept=True, bip67=bip67, descriptor=True)
+ po = BasicPSBT().parse(fake_ms_txn(2, 1, 2, keys, inp_af=AF_P2WSH,
+ psbt_v2=True, bip67=bip67))
+ our_xfp = struct.pack('<I', simulator_fixed_xfp)
+ for idx, inp in enumerate(po.inputs):
+ foreign = [pk for pk, path in inp.bip32_paths.items() if path[:4] != our_xfp]
+ inp.part_sigs = {pk: b'\x30' + pk + bytes(37) for pk in foreign[:2-idx]}
+ inp = po.inputs[0]
+ script = inp.witness_script
+ script_keys = [script[p+1:p+34] for p in range(1, len(script)-2, 34)]
+ # Put the unrelated key first in BIP-67 order to expose selection by raw sorting.
+ for n in range(1, 256):
+ extra_pk = BIP32Node.from_master_secret(bytes([n]) * 32).sec()
+ if extra_pk < min(script_keys):
+ break
+ else:
+ raise AssertionError('could not find lexically smaller unrelated key')
+ if problem == 'wrong_key':
+ del inp.part_sigs[next(iter(inp.part_sigs))]
+ extra_sig = b'\x30' + bytes([0xaa]) * 70
+ inp.part_sigs[extra_pk] = extra_sig
+ raw = po.as_bytes()
+ if problem == 'wrong_key':
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ assert BasicPSBT().parse(signed).inputs[0] == inp
+ return
+ _, txn = try_sign(raw, finalize=True)
+ _, sd_txn, txid = try_sign_microsd(raw, finalize=True)
+ assert txid is not None
+ assert sd_txn == txn
+ tx = CTransaction()
+ tx.deserialize(BytesIO(txn))
+ expected = [inp.part_sigs[pk] for pk in script_keys if pk in inp.part_sigs][:2]
+ assert tx.wit.vtxinwit[0].scriptWitness.stack == [b''] + expected + [script]
+ assert extra_sig not in txn
+
+
+@pytest.mark.parametrize('presigned_first', [True, False])
+@pytest.mark.parametrize('all_signed', [False, True])
+def test_presigned_other_wallet(all_signed, presigned_first, clear_ms, import_ms_wallet,
+ fake_ms_txn, try_sign, try_sign_microsd):
+ # A completed input must not choose the wallet used to sign another input.
+ clear_ms()
+ keys_a = import_ms_wallet(2, 3, name='presigned', unique=1,
+ addr_fmt='p2sh-p2wsh', accept=True)
+ keys_b = import_ms_wallet(2, 3, name='signing', unique=2,
+ addr_fmt='p2sh-p2wsh', accept=True)
+ presigned = BasicPSBT().parse(fake_ms_txn(1, 1, 2, keys_a,
+ inp_af=AF_P2WSH_P2SH, psbt_v2=True)).inputs[0]
+ our_xfp = struct.pack('<I', simulator_fixed_xfp)
+ sig = b'\x30' + bytes(70)
+ presigned.part_sigs = {pk: sig for pk, path in presigned.bip32_paths.items()
+ if all_signed or path[:4] != our_xfp}
+
+ psbt = BasicPSBT().parse(fake_ms_txn(2, 1, 2, keys_b,
+ inp_af=AF_P2WSH_P2SH, psbt_v2=True))
+ idx = 0 if presigned_first else 1
+ presigned.my_index = idx
+ psbt.inputs[idx] = presigned
+ signing = psbt.inputs[1 - idx]
+ pk = next(pk for pk, path in signing.bip32_paths.items() if path[:4] != our_xfp)
+ signing.part_sigs = {pk: sig}
+ assert not psbt.xpubs
+ raw = psbt.as_bytes()
+
+ _, signed = try_sign(raw)
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[idx] == presigned
+ assert len(signed.inputs[1 - idx].part_sigs) == 2
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[idx] == presigned
+ assert len(signed.inputs[1 - idx].part_sigs) == 2
+
+
+@pytest.mark.parametrize('all_signed', [False, True])
+@pytest.mark.parametrize('multisig_payment', [False, True])
+def test_presigned_multisig_with_singlesig(all_signed, multisig_payment, clear_ms,
+ import_ms_wallet, fake_ms_txn, fake_txn, start_sign, end_sign, cap_story,
+ sim_exec, try_sign, try_sign_microsd):
+ clear_ms()
+ keys = import_ms_wallet(2, 3, name='presigned', unique=1,
+ addr_fmt='p2sh-p2wsh', accept=True)
+ presigned = BasicPSBT().parse(fake_ms_txn(1, 1, 2, keys,
+ inp_af=AF_P2WSH_P2SH, psbt_v2=True)).inputs[0]
+ our_xfp = struct.pack('<I', simulator_fixed_xfp)
+ presigned.part_sigs = {pk: b'\x30' + bytes(70)
+ for pk, path in presigned.bip32_paths.items()
+ if all_signed or path[:4] != our_xfp}
+ psbt = BasicPSBT().parse(fake_txn(2, 1, segwit_in=True, psbt_v2=True))
+ psbt.inputs[0] = presigned
+ if multisig_payment:
+ # A payment to another registered wallet must not be checked as change
+ # for the wallet of the presigned input.
+ dest_keys = import_ms_wallet(2, 3, name='destination', unique=2,
+ addr_fmt='p2sh-p2wsh', accept=True)
+ payment = BasicPSBT().parse(fake_ms_txn(2, 1, 2, dest_keys,
+ inp_af=AF_P2WSH_P2SH, change_outputs=[0], psbt_v2=True))
+ psbt.outputs[0] = payment.outputs[0]
+ assert not psbt.xpubs
+ raw = psbt.as_bytes()
+
+ start_sign(raw)
+ title, story = cap_story()
+ assert title == 'OK TO SEND?', story
+ # Exercise the policy check against the actual parsed transaction before
+ # approval: only singlesig needs signing, so a multisig-only rule must fail.
+ assert sim_exec("""
+from auth import UserAuthorizedAction
+from hsm import ApprovalRule
+from chains import current_chain
+p = UserAuthorizedAction.active_request.psbt
+try:
+ ApprovalRule({'wallet': 'presigned'}, 0).matches_transaction(
+ p, {}, 0, False, current_chain())
+except AssertionError as exc:
+ RV.write(str(exc))
+else:
+ RV.write('accepted')
+""") == 'not multisig'
+ assert sim_exec("""
+from auth import UserAuthorizedAction
+from hsm import ApprovalRule
+from chains import current_chain
+p = UserAuthorizedAction.active_request.psbt
+assert p.active_multisig is None
+assert not p.outputs[0].is_change
+assert ApprovalRule({'wallet': '1'}, 0).matches_transaction(p, {}, 0, False, current_chain())
+RV.write('ok')
+""") == 'ok'
+ signed = BasicPSBT().parse(end_sign())
+ assert signed.inputs[0] == presigned
+ assert signed.inputs[1].part_sigs
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == presigned
+ assert signed.inputs[1].part_sigs
+
+
+@pytest.mark.parametrize('signature_count', [1, 2, 3])
+def test_multisig_missing_witness_script(signature_count, clear_ms, import_ms_wallet,
+ fake_ms_txn, try_sign, try_sign_microsd):
+ clear_ms()
+ keys = import_ms_wallet(2, 3, addr_fmt='p2wsh', accept=True)
+ psbt = BasicPSBT().parse(fake_ms_txn(2, 1, 2, keys, inp_af=AF_P2WSH,
+ psbt_v2=True))
+ our_xfp = struct.pack('<I', simulator_fixed_xfp)
+ for idx, inp in enumerate(psbt.inputs):
+ # Put our key last so the one-signature case still needs us to sign.
+ pubkeys = sorted(inp.bip32_paths,
+ key=lambda pk: inp.bip32_paths[pk][:4] == our_xfp)
+ count = signature_count if idx == 0 else 1
+ inp.part_sigs = {pk: b'\x30' + bytes(70) for pk in pubkeys[:count]}
+
+ inp = psbt.inputs[0]
+ inp.redeem_script = inp.witness_script
+ inp.witness_script = None
+ raw = psbt.as_bytes()
+
+ if signature_count == 1:
+ # Inputs needing our signature must still provide the witness script.
+ with pytest.raises(CCProtoError, match='Need witness script for input #0'):
+ try_sign(raw)
+ return
+
+ # A presigned input with its script in the wrong field must stay a PSBT.
+ _, signed = try_sign(raw)
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == inp
+ assert len(signed.inputs[1].part_sigs) == 2
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == inp
+ assert len(signed.inputs[1].part_sigs) == 2
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+
+
# EOF
### testing/test_sign.py
@@ -1013,7 +1013,7 @@ def test_sign_wutxo(start_sign, set_seed_words, end_sign, cap_story, sim_exec, s
assert 'Network fee 0.00000500 XTN' in story
# check we understood it right
- ex = dict( had_witness=False, num_inputs=1, num_outputs=1, sw_inputs=[None],
+ ex = dict( had_witness=False, num_inputs=1, num_outputs=1, sw_inputs=[False],
miner_fee=500, warnings_expected=0,
lock_time=1442308, total_value_out=99500,
total_value_in=100000)
@@ -4130,16 +4130,21 @@ def test_mk4_done_signing_infinite_loop(goto_home, try_sign, fake_txn, enable_hw
@pytest.mark.bitcoind
-def test_finalize_with_foreign_inputs(bitcoind, bitcoind_d_sim_watch, start_sign, end_sign,
- cap_story, try_sign_microsd):
+@pytest.mark.parametrize('foreign_type', ['p2pkh', 'p2wpkh', 'p2sh-p2wpkh'])
+@pytest.mark.parametrize('include_paths', [True, False, 'claimed_ours'])
+def test_finalize_with_foreign_inputs(foreign_type, include_paths, bitcoind,
+ bitcoind_d_sim_watch, start_sign, end_sign,
+ cap_story, try_sign, try_sign_microsd, use_regtest):
# foreign inputs that have partial sigs filled
# we still do not care about final_scriptsig & final_scriptwitness PSBT fields
+ use_regtest()
dest_address = bitcoind.supply_wallet.getnewaddress()
alice = bitcoind.create_wallet(wallet_name="alice")
bob = bitcoind.create_wallet(wallet_name="bob")
cc = bitcoind_d_sim_watch
- alice_addr = alice.getnewaddress()
- bob_addr = bob.getnewaddress()
+ foreign_af = {'p2pkh': 'legacy', 'p2wpkh': 'bech32', 'p2sh-p2wpkh': 'p2sh-segwit'}[foreign_type]
+ alice_addr = alice.getnewaddress('', foreign_af)
+ bob_addr = bob.getnewaddress('', foreign_af)
cc_addr = cc.getnewaddress()
# fund all addresses
for addr in (alice_addr, bob_addr, cc_addr):
@@ -4164,18 +4169,23 @@ def test_finalize_with_foreign_inputs(bitcoind, bitcoind_d_sim_watch, start_sign
# join PSBTs to one
the_psbt = bitcoind.supply_wallet.joinpsbts(psbt_list)
- # bitcoin core would just fill finalscriptwitness, we need partial signatures
- # just add dummy signatures and remove
+ # keep real partial signatures; Coldcard has to place them itself
+ for wallet in (alice, bob):
+ the_psbt = wallet.walletprocesspsbt(the_psbt, True, 'ALL', True, False)['psbt']
pp = BasicPSBT().parse(base64.b64decode(the_psbt))
- for i in pp.inputs:
- assert len(i.bip32_paths) == 1 # single sigs
- der = list(i.bip32_paths.values())[0]
- if der[:4].hex().upper() == xfp2str(simulator_fixed_xfp):
- # our key
+ foreign_inputs = {}
+ for idx, inp in enumerate(pp.inputs):
+ if any(path[:4].hex().upper() == xfp2str(simulator_fixed_xfp)
+ for path in inp.bip32_paths.values()):
continue
- pubkey = list(i.bip32_paths.keys())[0]
- assert not i.part_sigs # empty
- i.part_sigs[pubkey] = os.urandom(71) # dummy sig
+ foreign_inputs[idx] = inp
+ if not include_paths:
+ inp.bip32_paths.clear()
+ elif include_paths == 'claimed_ours':
+ # ownership claims are not what makes an input finalizable
+ inp.bip32_paths = {pk: struct.pack('<I', simulator_fixed_xfp) + path[4:]
+ for pk, path in inp.bip32_paths.items()}
+ assert len(foreign_inputs) == 2
# USB works and our signature is added (but only if we do not finalize)
psbt = pp.as_bytes()
@@ -4185,11 +4195,318 @@ def test_finalize_with_foreign_inputs(bitcoind, bitcoind_d_sim_watch, start_sign
for i in BasicPSBT().parse(signed).inputs:
assert i.part_sigs
- try_sign_microsd(psbt, finalize=True, accept=True)
+ start_sign(psbt, finalize=True)
+ usb_txn = end_sign(accept=True, finalize=True)
+ _, sd_txn, _ = try_sign_microsd(psbt, finalize=True, accept=True)
title, story = cap_story()
assert title == "PSBT Signed"
assert "Finalized transaction (ready for broadcast)" in story
+ for raw in (usb_txn, sd_txn):
+ txn = CTransaction()
+ txn.deserialize(BytesIO(raw))
+ for idx, inp in foreign_inputs.items():
+ pubkey, sig = next(iter(inp.part_sigs.items()))
+ if foreign_type == 'p2pkh':
+ assert txn.vin[idx].scriptSig == bytes([len(sig)]) + sig + bytes([len(pubkey)]) + pubkey
+ assert not txn.wit.vtxinwit or not txn.wit.vtxinwit[idx].scriptWitness.stack
+ else:
+ redeem = inp.redeem_script
+ assert txn.vin[idx].scriptSig == (bytes([len(redeem)]) + redeem if redeem else b'')
+ assert txn.wit.vtxinwit[idx].scriptWitness.stack == [sig, pubkey]
+ result, = bitcoind.rpc.testmempoolaccept([raw.hex()])
+ assert result['allowed'], result
+
+ if foreign_type == 'p2sh-p2wpkh':
+ # a redeem script the UTXO does not commit to cannot be finalized,
+ # but it is not ours to reject either
+ bad = BasicPSBT().parse(psbt)
+ idx = next(iter(foreign_inputs))
+ redeem = bad.inputs[idx].redeem_script
+ bad.inputs[idx].redeem_script = redeem[:-1] + bytes([redeem[-1] ^ 1])
+ raw = bad.as_bytes()
+ _, signed = try_sign(raw)
+ assert BasicPSBT().parse(signed).inputs[idx].part_sigs
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+
+
+@pytest.mark.parametrize('include_paths', [True, False, 'claimed_ours'])
+def test_presigned_bad_redeem(include_paths, fake_txn, try_sign, try_sign_microsd):
+ node = BIP32Node.from_master_secret(bytes(range(32)))
+ foreign = BasicPSBT().parse(fake_txn(1, 1, master_xpub=node.hwif(),
+ segwit_in=True, wrapped=True, psbt_v2=True)).inputs[0]
+ pubkey = next(iter(foreign.bip32_paths))
+ foreign.part_sigs = {pubkey: b'\x30' + bytes(70)}
+ redeem = foreign.redeem_script
+ foreign.redeem_script = redeem[:-1] + bytes([redeem[-1] ^ 1])
+ if not include_paths:
+ foreign.bip32_paths.clear()
+ elif include_paths == 'claimed_ours':
+ path = foreign.bip32_paths[pubkey]
+ foreign.bip32_paths[pubkey] = struct.pack('<I', simulator_fixed_xfp) + path[4:]
+
+ psbt = BasicPSBT().parse(fake_txn(2, 1, segwit_in=True, psbt_v2=True))
+ psbt.inputs[0] = foreign
+ raw = psbt.as_bytes()
+ _, signed = try_sign(raw)
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == foreign
+ assert signed.inputs[1].part_sigs
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == foreign
+ assert signed.inputs[1].part_sigs
+
+
+@pytest.mark.parametrize('style', ['p2wpkh', 'p2wsh', 'p2tr'])
+def test_foreign_segwit_signing(style, fake_txn, try_sign, cap_story):
+ # recognizing a foreign witness program must not make it finalizable
+ psbt = BasicPSBT().parse(fake_txn(2, 1, segwit_in=True))
+ foreign = psbt.inputs[0]
+ foreign.bip32_paths.clear()
+ foreign.witness_utxo = CTxOut(100000000, fake_dest_addr(style)).serialize()
+ if style == 'p2tr':
+ # opaque foreign signature data must survive PSBT round-tripping
+ foreign.taproot_key_sig = bytes(64)
+
+ raw = psbt.as_bytes()
+ _, signed = try_sign(raw)
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == foreign
+ assert signed.inputs[1].part_sigs
+
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, story = cap_story()
+ assert 'No signature on input #0' in story
+
+
+@pytest.mark.parametrize('style', ['p2pk', 'p2pkh', 'p2wpkh', 'p2sh-p2wpkh'])
+@pytest.mark.parametrize('problem', ['utxo', 'signature', 'extra_signature',
+ 'wrong_pubkey', 'forged_xfp'])
+def test_presigned_singlesig_finalization_data(style, problem, fake_txn, try_sign,
+ try_sign_microsd):
+ # missing, ambiguous or mismatched signature data leaves the input in PSBT form
+ node = BIP32Node.from_master_secret(bytes(range(32)))
+ foreign = BasicPSBT().parse(fake_txn(1, 1, master_xpub=node.hwif(), psbt_v2=True,
+ p2pk_in=style == 'p2pk', segwit_in=style in ('p2wpkh', 'p2sh-p2wpkh'),
+ wrapped=style == 'p2sh-p2wpkh')).inputs[0]
+ pubkey = next(iter(foreign.bip32_paths))
+ foreign.part_sigs = {pubkey: b'\x30' + bytes(70)}
+ foreign.bip32_paths.clear()
+ if problem == 'utxo':
+ foreign.utxo = foreign.witness_utxo = None
+ elif problem == 'signature':
+ foreign.part_sigs.clear()
+ else:
+ other = node.subkey_for_path('1/0').sec()
+ foreign.part_sigs[other] = b'\x30' + bytes(70)
+ if problem in ('wrong_pubkey', 'forged_xfp'):
+ del foreign.part_sigs[pubkey]
+ if problem == 'forged_xfp':
+ # claiming our fingerprint must not make the mismatch finalizable
+ foreign.bip32_paths = {other: struct.pack('<III', simulator_fixed_xfp, 0, 0)}
+
+ psbt = BasicPSBT().parse(fake_txn(2, 1, segwit_in=True, psbt_v2=True))
+ psbt.inputs[0] = foreign
+ raw = psbt.as_bytes()
+
+ _, signed = try_sign(raw)
+ assert BasicPSBT().parse(signed).inputs[0] == foreign
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == foreign
+ assert signed.inputs[1].part_sigs
+
+
+@pytest.mark.parametrize('wrapped', [False, True])
+@pytest.mark.parametrize('encoding', ['uncompressed', 'bad_prefix'])
+def test_presigned_segwit_unsupported_pubkey(wrapped, encoding, fake_txn, try_sign,
+ try_sign_microsd):
+ # v0 witness programs only commit to compressed keys; anything else stays a PSBT
+ node = BIP32Node.from_master_secret(bytes(range(32)))
+ pubkey = node.sec(compressed=False) if encoding == 'uncompressed' else b'\x04' + node.sec()[1:]
+ psbt = BasicPSBT().parse(fake_txn(2, 1, segwit_in=True, psbt_v2=True))
+ inp = psbt.inputs[0]
+ script = b'\x00\x14' + hash160(pubkey)
+ if wrapped:
+ inp.redeem_script = script
+ script = b'\xa9\x14' + hash160(script) + b'\x87'
+ utxo = CTxOut()
+ utxo.deserialize(BytesIO(inp.witness_utxo))
+ utxo.scriptPubKey = script
+ inp.witness_utxo = utxo.serialize()
+ inp.bip32_paths.clear()
+ inp.part_sigs = {pubkey: b'\x30' + bytes(70)}
+ raw = psbt.as_bytes()
+
+ _, signed = try_sign(raw)
+ assert BasicPSBT().parse(signed).inputs[0] == inp
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ assert BasicPSBT().parse(signed).inputs[0] == inp
+
+
+def test_presigned_nested_missing_redeem(fake_txn, try_sign, try_sign_microsd):
+ # without the redeem script we cannot tell what the scriptSig must hold
+ psbt = BasicPSBT().parse(fake_txn(2, 1, segwit_in=True, wrapped=True))
+ inp = psbt.inputs[0]
+ pubkey = next(iter(inp.bip32_paths))
+ inp.part_sigs = {pubkey: b'\x30' + bytes(70)}
+ inp.redeem_script = None
+ raw = psbt.as_bytes()
+
+ _, signed = try_sign(raw)
+ assert BasicPSBT().parse(signed).inputs[0] == inp
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ assert BasicPSBT().parse(signed).inputs[0] == inp
+
+
+def test_foreign_p2wsh_script_mismatch(fake_txn, try_sign, try_sign_microsd, cap_story):
+ # a witness script that does not hash to the witness program is never
+ # finalized: script-to-wallet validation is what would have caught it
+ psbt = BasicPSBT().parse(fake_txn(2, 1, segwit_in=True, psbt_v2=True))
+ inp = psbt.inputs[0]
+ pubkey = next(iter(inp.bip32_paths))
+ inp.bip32_paths.clear()
+ inp.witness_script = bytes(range(34))
+ inp.part_sigs = {pubkey: b'\x30' + bytes(70)}
+
+ utxo = CTxOut()
+ utxo.deserialize(BytesIO(inp.witness_utxo))
+ utxo.scriptPubKey = b'\x00\x20' + bytes(32) # not sha256(witness_script)
+ inp.witness_utxo = utxo.serialize()
+ raw = psbt.as_bytes()
+
+ _, signed = try_sign(raw)
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == inp
+ assert signed.inputs[1].part_sigs
+
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, story = cap_story()
+ assert 'Incomplete signature set on input #0' in story
+
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ assert BasicPSBT().parse(signed).inputs[0] == inp
+
+
+def test_finalize_mixed_foreign_inputs(fake_txn, try_sign, try_sign_microsd, cap_story):
+ # one unusable foreign input blocks the whole transaction, even beside
+ # a foreign input that is perfectly finalizable on its own
+ _, signed = try_sign(fake_txn(3, 1, segwit_in=True))
+ psbt = BasicPSBT().parse(signed)
+ good, bad, ours = psbt.inputs
+
+ good.bip32_paths.clear() # signature matches its script
+
+ sig, = bad.part_sigs.values()
+ bad.part_sigs = {b'\x02' + bytes(32): sig} # key cannot hash to the script
+ bad.bip32_paths.clear()
+
+ ours.part_sigs.clear()
+ raw = psbt.as_bytes()
+
+ _, out = try_sign(raw)
+ out = BasicPSBT().parse(out)
+ assert out.inputs[0] == good
+ assert out.inputs[1] == bad
+ assert out.inputs[2].part_sigs
+
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, story = cap_story()
+ assert 'No signature on input #1' in story
+
+ _, out, txid = try_sign_microsd(raw)
+ assert txid is None
+
+
+@pytest.mark.parametrize('style', ['bad_p2sh_p2wsh', 'unknown_spk', 'op_return'])
+def test_foreign_unclassifiable_input(style, fake_txn, try_sign, try_sign_microsd, cap_story):
+ # analyze_input() cannot work out what these are, so they can never be
+ # finalized; our own input is still signed and comes back as a PSBT
+ psbt = BasicPSBT().parse(fake_txn(2, 1, segwit_in=True, psbt_v2=True))
+ inp = psbt.inputs[0]
+ inp.bip32_paths.clear()
+
+ if style == 'bad_p2sh_p2wsh':
+ # redeem script must be the witness program of the witness script
+ inp.witness_script = bytes(range(34))
+ inp.redeem_script = b'\x00\x20' + bytes(32)
+ spk = b'\xa9\x14' + hash160(inp.redeem_script) + b'\x87'
+ elif style == 'unknown_spk':
+ spk = b'\x51\x52\x53'
+ else:
+ spk = b'\x6a\x04test'
+
+ utxo = CTxOut()
+ utxo.deserialize(BytesIO(inp.witness_utxo))
+ utxo.scriptPubKey = spk
+ inp.witness_utxo = utxo.serialize()
+ raw = psbt.as_bytes()
+
+ _, signed = try_sign(raw)
+ signed = BasicPSBT().parse(signed)
+ assert signed.inputs[0] == inp
+ assert signed.inputs[1].part_sigs
+
+ with pytest.raises(CCProtoError, match='PSBT output failed'):
+ try_sign(raw, finalize=True)
+ _, story = cap_story()
+ assert 'No signature on input #0' in story
+
+ _, signed, txid = try_sign_microsd(raw)
+ assert txid is None
+ assert BasicPSBT().parse(signed).inputs[0] == inp
+
+
+@pytest.mark.parametrize('style', ['p2pkh', 'p2wpkh', 'p2sh-p2wpkh', 'p2pk',
+ 'p2pk-uncompressed'])
+def test_finalize_own_presigned_input(style, fake_txn, try_sign):
+ # second pass over a PSBT we signed before: our earlier signature is in
+ # part_sigs now, and finalization must still place it correctly
+ # - p2pk-uncompressed: the compressed-key rule applies to segwit only
+ kws = {'p2pkh': {},
+ 'p2wpkh': dict(segwit_in=True),
+ 'p2sh-p2wpkh': dict(segwit_in=True, wrapped=True),
+ 'p2pk': dict(p2pk_in='compressed'),
+ 'p2pk-uncompressed': dict(p2pk_in='uncompressed')}[style]
+ _, signed = try_sign(fake_txn(2, 1, **kws))
+
+ psbt = BasicPSBT().parse(signed)
+ assert all(len(i.part_sigs) == 1 for i in psbt.inputs)
+ pubkey, sig = next(iter(psbt.inputs[0].part_sigs.items()))
+ redeem_script = psbt.inputs[0].redeem_script
+ psbt.inputs[1].part_sigs.clear()
+
+ _, txn = try_sign(psbt.as_bytes(), finalize=True)
+ tx = CTransaction()
+ tx.deserialize(BytesIO(txn))
+ if style.startswith('p2pk-') or style == 'p2pk':
+ # pubkey is already in the scriptPubKey, so scriptSig is just the sig
+ assert tx.vin[0].scriptSig == bytes([len(sig)]) + sig
+ elif kws.get('segwit_in'):
+ expect = bytes([len(redeem_script)]) + redeem_script if kws.get('wrapped') else b''
+ assert tx.vin[0].scriptSig == expect
+ assert tx.wit.vtxinwit[0].scriptWitness.stack == [sig, pubkey]
+ else:
+ assert tx.vin[0].scriptSig == bytes([len(sig)]) + sig + bytes([len(pubkey)]) + pubkey
+
@pytest.mark.parametrize("psbt_v2", [False, True])
def test_txn_v3(psbt_v2, fake_txn, start_sign, end_sign, cap_story):Why this scored 74/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.