From 92cd45b6e48d4847a515274321958a7c7cfc4ccf Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 28 Sep 2026 07:57:04 +0000 Subject: [PATCH 01/13] test: reuse create_outpoints in wallet_signer --- test/functional/wallet_signer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/functional/wallet_signer.py b/test/functional/wallet_signer.py index 20a5a3f3fcb4..073b4e51eb93 100755 --- a/test/functional/wallet_signer.py +++ b/test/functional/wallet_signer.py @@ -151,7 +151,7 @@ def test_valid_signer(self): ) self.log.info('Prepare mock PSBT') - self.nodes[0].sendtoaddress(address4, 1) + self.create_outpoints(self.nodes[0], outputs=[{address4: 1}]) self.generate(self.nodes[0], 1) # Load private key into wallet to generate a signed PSBT for the mock @@ -231,7 +231,7 @@ def test_disconnected_signer(self): assert_equal(hww.getwalletinfo()["external_signer"], True) # Fund wallet - self.nodes[0].sendtoaddress(hww.getnewaddress(address_type="bech32m"), 1) + self.create_outpoints(self.nodes[0], outputs=[{hww.getnewaddress(address_type="bech32m"): 1}]) self.generate(self.nodes[0], 1) # Restart node with no signer connected From b94d560e1d82779cee48bdf3ae97d9e2823e5dee Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Fri, 28 Aug 2026 08:36:36 +0000 Subject: [PATCH 02/13] test: have external signer mock use a wallet The external signer mock previously replayed a PSBT that the test prepared in advance. This makes it difficult to test more complicated scenarios like a misbehaving wallet and (MuSig2) multisig. Instead, give the mock its own descriptor wallet. The test provides a dedicated node for this wallet and keeps it offline, so the mock can't cheat by e.g. inspecting the UTXO set. The mock creates the wallet on first use and signs with walletprocesspsbt. wallet_signer.py now funds all four descriptor types and spends them in a single transaction, exercising every signing code path. --- test/functional/mocks/signer.py | 50 ++++++++++++++---- test/functional/wallet_signer.py | 89 +++++++++++++------------------- 2 files changed, 76 insertions(+), 63 deletions(-) diff --git a/test/functional/mocks/signer.py b/test/functional/mocks/signer.py index a13c97d1216f..d668b0da65ed 100755 --- a/test/functional/mocks/signer.py +++ b/test/functional/mocks/signer.py @@ -8,6 +8,17 @@ import argparse import json +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) + +from test_framework.authproxy import AuthServiceProxy, JSONRPCException + +# Master private key for the tpub in getdescriptors below. Used by signtx, +# which imports the keys into a wallet on the offline node provided by the +# test and lets it do the actual signing. +tprv = "tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK" + +MOCK_WALLET = "mock" + def perform_pre_checks(): mock_result_path = os.path.join(os.getcwd(), "mock_result") if os.path.isfile(mock_result_path): @@ -56,20 +67,41 @@ def displayaddress(args): return sys.stdout.write(json.dumps({"address": expected_desc[args.desc]})) +def get_mock_wallet(): + """RPC connection to the wallet holding our private keys, created on + first use. The test provides a dedicated offline node for it and passes + the node's RPC URL via a file in our working directory.""" + with open(os.path.join(os.getcwd(), "mock_rpc_url"), "r", encoding="utf8") as f: + node_url = f.read().strip() + node = AuthServiceProxy(node_url) + wallet = AuthServiceProxy(f"{node_url}/wallet/{MOCK_WALLET}") + try: + node.loadwallet(filename=MOCK_WALLET) + return wallet + except JSONRPCException as e: + if e.error["code"] == -35: # RPC_WALLET_ALREADY_LOADED + return wallet + if e.error["code"] != -18: # RPC_WALLET_NOT_FOUND + raise + node.createwallet(wallet_name=MOCK_WALLET, blank=True) + requests = [] + for desc in [f"pkh({tprv}/<0;1>/*)", f"sh(wpkh({tprv}/<0;1>/*))", f"wpkh({tprv}/<0;1>/*)", f"tr({tprv}/<0;1>/*)"]: + checksum = node.getdescriptorinfo(descriptor=desc)["checksum"] + requests.append({"desc": f"{desc}#{checksum}", "timestamp": "now", "range": [0, 99]}) + result = wallet.importdescriptors(requests=requests) + assert all(r["success"] for r in result) + return wallet + def signtx(args): if args.fingerprint != "00000001": return sys.stdout.write(json.dumps({"error": "Unexpected fingerprint", "fingerprint": args.fingerprint})) - with open(os.path.join(os.getcwd(), "mock_psbt"), "r") as f: - mock_psbt = f.read() + psbt = args.psbt + wallet = get_mock_wallet() + result = wallet.walletprocesspsbt(psbt=psbt, sign=True, bip32derivs=False, finalize=False) + reply = result["psbt"] - if args.fingerprint == "00000001" : - sys.stdout.write(json.dumps({ - "psbt": mock_psbt, - "complete": True - })) - else: - sys.stdout.write(json.dumps({"psbt": args.psbt})) + sys.stdout.write(json.dumps({"psbt": reply})) parser = argparse.ArgumentParser(prog='./signer.py', description='External signer mock') parser.add_argument('--fingerprint') diff --git a/test/functional/wallet_signer.py b/test/functional/wallet_signer.py index 073b4e51eb93..88fe8e9c7193 100755 --- a/test/functional/wallet_signer.py +++ b/test/functional/wallet_signer.py @@ -36,14 +36,26 @@ def mock_multi_signers_path(self): return sys.executable + " " + path def set_test_params(self): - self.num_nodes = 2 + self.num_nodes = 3 self.noban_tx_relay = True # faster tx relay self.extra_args = [ [], [f"-signer={self.mock_signer_path()}", '-keypool=10'], + # Node for the signer mock's wallet, kept offline so the mock + # can't cheat by e.g. inspecting the UTXO set + ["-maxconnections=0"], ] + def setup_network(self): + self.setup_nodes() + # Leave the signer mock's node disconnected + self.connect_nodes(0, 1) + + def sync_except_mock(self): + """Sync all nodes except the signer mock's, which never receives blocks.""" + self.sync_all(self.nodes[0:2]) + def skip_test_if_missing_module(self): self.skip_if_no_external_signer() self.skip_if_no_wallet() @@ -55,7 +67,16 @@ def set_mock_result(self, node, res): def clear_mock_result(self, node): os.remove(os.path.join(node.cwd, "mock_result")) + def init_mock_node(self): + """Hand the signer mock its dedicated offline node, on which it + creates the wallet it signs with.""" + signer_node = self.nodes[2] + assert_equal(signer_node.getconnectioncount(), 0) + with open(os.path.join(self.nodes[1].cwd, "mock_rpc_url"), "w") as f: + f.write(signer_node.url) + def run_test(self): + self.init_mock_node() self.test_valid_signer() self.test_disconnected_signer() self.restart_node(1, [f"-signer={self.mock_invalid_signer_path()}", "-keypool=10"]) @@ -150,73 +171,33 @@ def test_valid_signer(self): hww.walletdisplayaddress, address_fail ) - self.log.info('Prepare mock PSBT') - self.create_outpoints(self.nodes[0], outputs=[{address4: 1}]) - self.generate(self.nodes[0], 1) - - # Load private key into wallet to generate a signed PSBT for the mock - self.nodes[1].createwallet(wallet_name="mock", disable_private_keys=False, blank=True) - mock_wallet = self.nodes[1].get_wallet_rpc("mock") - assert mock_wallet.getwalletinfo()['private_keys_enabled'] - - result = mock_wallet.importdescriptors([{ - "desc": "tr([00000001/86h/1h/0']tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0/*)#7ew68cn8", - "timestamp": 0, - "range": [0,1], - "internal": False, - "active": True - }, - { - "desc": "tr([00000001/86h/1h/0']tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/*)#0dtm6drl", - "timestamp": 0, - "range": [0, 0], - "internal": True, - "active": True - }]) - assert_equal(result[0], {'success': True}) - assert_equal(result[1], {'success': True}) - assert_equal(mock_wallet.getwalletinfo()["txcount"], 1) - dest = self.nodes[0].getnewaddress(address_type='bech32') - mock_psbt = mock_wallet.walletcreatefundedpsbt([], {dest:0.5}, 0, {'replaceable': True}, True)['psbt'] - mock_psbt_signed = mock_wallet.walletprocesspsbt(psbt=mock_psbt, sign=True, sighashtype="ALL", bip32derivs=True) - mock_tx = mock_psbt_signed["hex"] - assert mock_wallet.testmempoolaccept([mock_tx])[0]["allowed"] - + self.log.info('Fund hww wallet') + self.create_outpoints(self.nodes[0], outputs=[{address: 1} for address in [address1, address2, address3, address4]]) + self.generate(self.nodes[0], 1, sync_fun=self.sync_except_mock) assert_equal(hww.getwalletinfo()["txcount"], 1) - assert hww.testmempoolaccept([mock_tx])[0]["allowed"] - - with open(os.path.join(self.nodes[1].cwd, "mock_psbt"), "w") as f: - f.write(mock_psbt_signed["psbt"]) + dest = self.nodes[0].getnewaddress(address_type='bech32') self.log.info('Test send using hww1') - # Don't broadcast transaction yet so the RPC returns the raw hex - res = hww.send(outputs={dest:0.5},add_to_wallet=False) + # Spend all four address types at once. Don't broadcast the transaction + # yet so the RPC returns the raw hex. + res = hww.send(outputs={dest:3.5}, add_to_wallet=False) assert res["complete"] - assert_equal(res["hex"], mock_tx) + assert_equal(len(hww.decoderawtransaction(res["hex"])["vin"]), 4) + assert hww.testmempoolaccept([res["hex"]])[0]["allowed"] self.log.info('Test sendall using hww1') - res = hww.sendall(recipients=[{dest:0.5}, hww.getrawchangeaddress()], add_to_wallet=False) + res = hww.sendall(recipients=[{dest:3.5}, hww.getrawchangeaddress()], add_to_wallet=False) assert res["complete"] - assert_equal(res["hex"], mock_tx) + assert hww.testmempoolaccept([res["hex"]])[0]["allowed"] # Broadcast transaction so we can bump the fee hww.sendrawtransaction(res["hex"]) - self.log.info('Prepare fee bumped mock PSBT') - - # Now that the transaction is broadcast, bump fee in mock wallet: - orig_tx_id = res["txid"] - mock_psbt_bumped = mock_wallet.psbtbumpfee(orig_tx_id)["psbt"] - mock_psbt_bumped_signed = mock_wallet.walletprocesspsbt(psbt=mock_psbt_bumped, sign=True, sighashtype="ALL", bip32derivs=True) - - with open(os.path.join(self.nodes[1].cwd, "mock_psbt"), "w") as f: - f.write(mock_psbt_bumped_signed["psbt"]) - self.log.info('Test bumpfee using hww1') - # Bump fee + orig_tx_id = res["txid"] res = hww.bumpfee(orig_tx_id) assert_greater_than(res["fee"], res["origfee"]) assert_equal(res["errors"], []) @@ -232,7 +213,7 @@ def test_disconnected_signer(self): # Fund wallet self.create_outpoints(self.nodes[0], outputs=[{hww.getnewaddress(address_type="bech32m"): 1}]) - self.generate(self.nodes[0], 1) + self.generate(self.nodes[0], 1, sync_fun=self.sync_except_mock) # Restart node with no signer connected self.log.debug(f"-signer={self.mock_no_connected_signer_path()}") From d95f9f42e86934e1121249e0d5e236474b75312c Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 28 Sep 2026 08:12:30 +0000 Subject: [PATCH 03/13] test: add external signer mock sign modes Co-authored-by: brunoerg --- test/functional/mocks/signer.py | 8 ++++++++ test/functional/wallet_signer.py | 7 +++++++ 2 files changed, 15 insertions(+) diff --git a/test/functional/mocks/signer.py b/test/functional/mocks/signer.py index d668b0da65ed..722b7c109a9a 100755 --- a/test/functional/mocks/signer.py +++ b/test/functional/mocks/signer.py @@ -92,6 +92,14 @@ def get_mock_wallet(): assert all(r["success"] for r in result) return wallet +def get_mock_sign_mode(): + # The test can instruct us to sign in a specific, possibly misbehaving, way + sign_mode_path = os.path.join(os.getcwd(), "mock_sign_mode") + if os.path.isfile(sign_mode_path): + with open(sign_mode_path, "r", encoding="utf8") as f: + return f.read().strip() + return None + def signtx(args): if args.fingerprint != "00000001": return sys.stdout.write(json.dumps({"error": "Unexpected fingerprint", "fingerprint": args.fingerprint})) diff --git a/test/functional/wallet_signer.py b/test/functional/wallet_signer.py index 88fe8e9c7193..aeb916c97786 100755 --- a/test/functional/wallet_signer.py +++ b/test/functional/wallet_signer.py @@ -67,6 +67,13 @@ def set_mock_result(self, node, res): def clear_mock_result(self, node): os.remove(os.path.join(node.cwd, "mock_result")) + def set_mock_sign_mode(self, node, mode): + with open(os.path.join(node.cwd, "mock_sign_mode"), "w") as f: + f.write(mode) + + def clear_mock_sign_mode(self, node): + os.remove(os.path.join(node.cwd, "mock_sign_mode")) + def init_mock_node(self): """Hand the signer mock its dedicated offline node, on which it creates the wallet it signs with.""" From 12fa81f66c0ba4401ba8b4382c4f4b7529661fd1 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 28 Sep 2026 07:53:30 +0000 Subject: [PATCH 04/13] external_signer: require matching PSBT versions Reject a signer response with a different PSBT version and report the expected and returned versions. Document the requirement and test a v0 response to a v2 request. --- doc/external-signer.md | 2 ++ src/external_signer.cpp | 5 +++++ test/functional/mocks/signer.py | 7 +++++++ test/functional/wallet_signer.py | 14 ++++++++++++++ 4 files changed, 28 insertions(+) diff --git a/doc/external-signer.md b/doc/external-signer.md index 8b02edd6b8ab..1e6ffb528bda 100644 --- a/doc/external-signer.md +++ b/doc/external-signer.md @@ -148,6 +148,8 @@ A future extension could add an optional return field `reachable`, in case `` and MUST return a JSON object. On success, it MUST contain `{"psbt": ""}` updated to include any new signatures. On failure, it SHOULD contain `{"error": ""}`. Presence of a key `error` with value `null` is not considered an error. +The returned PSBT MUST use the same PSBT version as the request. + PSBT SHOULD include BIP32 derivations. The command SHOULD fail if none of the BIP32 derivations match a key owned by the device. The command SHOULD fail if the user cancels. diff --git a/src/external_signer.cpp b/src/external_signer.cpp index cb49cedc69c2..1a2bfcdb3da4 100644 --- a/src/external_signer.cpp +++ b/src/external_signer.cpp @@ -121,6 +121,11 @@ bool ExternalSigner::SignTransaction(PartiallySignedTransaction& psbtx, std::str return false; } + if (signer_psbtx->GetVersion() != psbtx.GetVersion()) { + error = strprintf("Signer returned PSBT version %u, expected %u", signer_psbtx->GetVersion(), psbtx.GetVersion()); + return false; + } + psbtx = *signer_psbtx; return true; diff --git a/test/functional/mocks/signer.py b/test/functional/mocks/signer.py index 722b7c109a9a..a4aa46005adf 100755 --- a/test/functional/mocks/signer.py +++ b/test/functional/mocks/signer.py @@ -104,11 +104,18 @@ def signtx(args): if args.fingerprint != "00000001": return sys.stdout.write(json.dumps({"error": "Unexpected fingerprint", "fingerprint": args.fingerprint})) + mode = get_mock_sign_mode() psbt = args.psbt wallet = get_mock_wallet() result = wallet.walletprocesspsbt(psbt=psbt, sign=True, bip32derivs=False, finalize=False) reply = result["psbt"] + if mode == "psbt_v0": + # Return the same transaction as a v0 PSBT. + tx = wallet.finalizepsbt(reply)["hex"] + # The conversion discards signatures; the version check runs first. + reply = wallet.converttopsbt(tx, permitsigdata=True, psbt_version=0) + sys.stdout.write(json.dumps({"psbt": reply})) parser = argparse.ArgumentParser(prog='./signer.py', description='External signer mock') diff --git a/test/functional/wallet_signer.py b/test/functional/wallet_signer.py index aeb916c97786..66526e0e07bf 100755 --- a/test/functional/wallet_signer.py +++ b/test/functional/wallet_signer.py @@ -85,6 +85,7 @@ def init_mock_node(self): def run_test(self): self.init_mock_node() self.test_valid_signer() + self.test_signer_psbt_version() self.test_disconnected_signer() self.restart_node(1, [f"-signer={self.mock_invalid_signer_path()}", "-keypool=10"]) self.test_invalid_signer() @@ -210,6 +211,19 @@ def test_valid_signer(self): assert_equal(res["errors"], []) + def test_signer_psbt_version(self): + hww = self.nodes[1].get_wallet_rpc('hww') + inputs = self.create_outpoints(self.nodes[0], outputs=[{hww.getnewaddress(): 2}]) + self.generate(self.nodes[0], 1, sync_fun=self.sync_except_mock) + dest = self.nodes[0].getnewaddress() + + self.log.info('The signer must preserve the PSBT version') + self.set_mock_sign_mode(self.nodes[1], "psbt_v0") + with self.nodes[1].assert_debug_log(["Signer returned PSBT version 0, expected 2"]): + assert_raises_rpc_error(-25, "External signer failed to sign", hww.send, outputs={dest: 1.5}, inputs=inputs, add_inputs=False) + + self.clear_mock_sign_mode(self.nodes[1]) + def test_disconnected_signer(self): self.log.info('Test disconnected external signer') From 2b801fc38452662f10c6ee998e86a1f90f97f482 Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Sun, 25 Oct 2026 02:06:36 +0000 Subject: [PATCH 05/13] external_signer: merge PSBT response instead of replacing Previously the PSBT returned by the external signer replaced the original wholesale, trusting the signer not to modify the transaction. Merge it instead. This rejects a response that describes a different transaction. Merging also supports signers that strip fields they don't need from their response. New tests cover both scenarios. Also test a signer that changes a PSBT v2 input sequence before signing. The transaction identifier used for merging ignores sequences, but the merge preserves the original sequence, leaving the signatures invalid for the wallet's transaction. This and a corrupted signature must leave the original transaction unchanged and return an incomplete PSBT. Test ECDSA and Schnorr signatures independently. Suggested in: https://github.com/bitcoin/bitcoin/pull/36114#issuecomment-6390058038 Co-authored-by: brunoerg --- src/external_signer.cpp | 5 ++- test/functional/mocks/signer.py | 50 +++++++++++++++++++++ test/functional/wallet_signer.py | 76 ++++++++++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 1 deletion(-) diff --git a/src/external_signer.cpp b/src/external_signer.cpp index 1a2bfcdb3da4..b4646e43e4df 100644 --- a/src/external_signer.cpp +++ b/src/external_signer.cpp @@ -126,7 +126,10 @@ bool ExternalSigner::SignTransaction(PartiallySignedTransaction& psbtx, std::str return false; } - psbtx = *signer_psbtx; + if (!psbtx.Merge(*signer_psbtx)) { + error = "Signer returned a PSBT for a different transaction"; + return false; + } return true; } diff --git a/test/functional/mocks/signer.py b/test/functional/mocks/signer.py index a4aa46005adf..e4f53f168f25 100755 --- a/test/functional/mocks/signer.py +++ b/test/functional/mocks/signer.py @@ -11,6 +11,14 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from test_framework.authproxy import AuthServiceProxy, JSONRPCException +from test_framework.psbt import ( + PSBT, + PSBT_IN_PARTIAL_SIG, + PSBT_IN_SEQUENCE, + PSBT_IN_TAP_KEY_SIG, + PSBT_OUT_AMOUNT, + PSBT_OUT_SCRIPT, +) # Master private key for the tpub in getdescriptors below. Used by signtx, # which imports the keys into a wallet on the offline node provided by the @@ -100,12 +108,32 @@ def get_mock_sign_mode(): return f.read().strip() return None +def tamper(psbt_b64, mode): + """Alter the transaction described by the (version 2) PSBT before signing + it, like a rogue or broken signer might.""" + psbt = PSBT.from_base64(psbt_b64) + if mode == "change_amount": + # Steal from the output by redirecting the value to fees + amount = int.from_bytes(psbt.o[0].map[PSBT_OUT_AMOUNT], "little", signed=True) + psbt.o[0].map[PSBT_OUT_AMOUNT] = (amount - 1).to_bytes(8, "little", signed=True) + elif mode == "change_script": + psbt.o[0].map[PSBT_OUT_SCRIPT] = bytes([0x51]) # OP_TRUE + elif mode == "remove_output": + psbt.o.pop() + elif mode == "change_sequence": + sequence = int.from_bytes(psbt.i[0].map[PSBT_IN_SEQUENCE], "little") + psbt.i[0].map[PSBT_IN_SEQUENCE] = (sequence ^ 1).to_bytes(4, "little") + return psbt.to_base64() + def signtx(args): if args.fingerprint != "00000001": return sys.stdout.write(json.dumps({"error": "Unexpected fingerprint", "fingerprint": args.fingerprint})) mode = get_mock_sign_mode() psbt = args.psbt + if mode in ("change_amount", "change_script", "remove_output", "change_sequence"): + psbt = tamper(psbt, mode) + wallet = get_mock_wallet() result = wallet.walletprocesspsbt(psbt=psbt, sign=True, bip32derivs=False, finalize=False) reply = result["psbt"] @@ -115,6 +143,28 @@ def signtx(args): tx = wallet.finalizepsbt(reply)["hex"] # The conversion discards signatures; the version check runs first. reply = wallet.converttopsbt(tx, permitsigdata=True, psbt_version=0) + elif mode == "strip": + # Return only the signatures, plus the fields required to describe + # the same transaction + signed = PSBT.from_base64(reply) + stripped = PSBT.from_base64(reply) + stripped.make_blank() + for signed_in, stripped_in in zip(signed.i, stripped.i): + for key, value in signed_in.map.items(): + if key == PSBT_IN_TAP_KEY_SIG or (isinstance(key, bytes) and key[0] == PSBT_IN_PARTIAL_SIG): + stripped_in.map[key] = value + reply = stripped.to_base64() + elif mode == "corrupt_signature": + signed = PSBT.from_base64(reply) + for psbt_in in signed.i: + for key, value in psbt_in.map.items(): + if key == PSBT_IN_TAP_KEY_SIG or (isinstance(key, bytes) and key[0] == PSBT_IN_PARTIAL_SIG): + # Change a signature byte while preserving the encoding + # and any trailing sighash byte. + signature = bytearray(value) + signature[-2] ^= 1 + psbt_in.map[key] = bytes(signature) + reply = signed.to_base64() sys.stdout.write(json.dumps({"psbt": reply})) diff --git a/test/functional/wallet_signer.py b/test/functional/wallet_signer.py index 66526e0e07bf..6b8982df47af 100755 --- a/test/functional/wallet_signer.py +++ b/test/functional/wallet_signer.py @@ -86,6 +86,9 @@ def run_test(self): self.init_mock_node() self.test_valid_signer() self.test_signer_psbt_version() + self.test_signer_stripped_psbt() + self.test_misbehaving_signer() + self.test_invalid_signer_signatures() self.test_disconnected_signer() self.restart_node(1, [f"-signer={self.mock_invalid_signer_path()}", "-keypool=10"]) self.test_invalid_signer() @@ -224,6 +227,79 @@ def test_signer_psbt_version(self): self.clear_mock_sign_mode(self.nodes[1]) + def test_signer_stripped_psbt(self): + self.log.info('Test external signer returning a stripped PSBT') + hww = self.nodes[1].get_wallet_rpc('hww') + + # Spend a segwit and a taproot UTXO, to cover both ECDSA and schnorr + # signatures + addresses = [hww.getnewaddress(address_type="bech32"), hww.getnewaddress(address_type="bech32m")] + inputs = self.create_outpoints(self.nodes[0], outputs=[{address: 1} for address in addresses]) + self.generate(self.nodes[0], 1, sync_fun=self.sync_except_mock) + dest = self.nodes[0].getnewaddress() + + self.log.info('The signer may strip fields it does not need') + self.set_mock_sign_mode(self.nodes[1], "strip") + res = hww.send(outputs={dest: 1.5}, inputs=inputs, add_inputs=False, add_to_wallet=False) + assert res["complete"] + assert hww.testmempoolaccept([res["hex"]])[0]["allowed"] + + self.clear_mock_sign_mode(self.nodes[1]) + + def test_misbehaving_signer(self): + self.log.info('Test misbehaving external signer') + hww = self.nodes[1].get_wallet_rpc('hww') + + # Spend a segwit and a taproot UTXO, to cover both ECDSA and schnorr + # signatures + addresses = [hww.getnewaddress(address_type="bech32"), hww.getnewaddress(address_type="bech32m")] + inputs = self.create_outpoints(self.nodes[0], outputs=[{address: 1} for address in addresses]) + self.generate(self.nodes[0], 1, sync_fun=self.sync_except_mock) + dest = self.nodes[0].getnewaddress() + + self.log.info('The signer must not tamper with the transaction') + for mode in ["change_amount", "change_script", "remove_output"]: + self.set_mock_sign_mode(self.nodes[1], mode) + with self.nodes[1].assert_debug_log(["Signer returned a PSBT for a different transaction"]): + assert_raises_rpc_error(-25, "External signer failed to sign", hww.send, outputs={dest: 1.5}, inputs=inputs, add_inputs=False) + + self.clear_mock_sign_mode(self.nodes[1]) + + # The same transaction is accepted from a well-behaved signer + res = hww.send(outputs={dest: 1.5}, inputs=inputs, add_inputs=False, add_to_wallet=False) + assert res["complete"] + + def test_invalid_signer_signatures(self): + hww = self.nodes[1].get_wallet_rpc('hww') + # Exercise ECDSA and schnorr verification independently. + for address_type in ["bech32", "bech32m"]: + self.log.info(f'Test invalid signer signatures for {address_type}') + inputs = self.create_outpoints(self.nodes[0], outputs=[{hww.getnewaddress(address_type=address_type): 1}]) + self.generate(self.nodes[0], 1, sync_fun=self.sync_except_mock) + dest = self.nodes[0].getnewaddress() + psbt = hww.walletcreatefundedpsbt(inputs=inputs, outputs={dest: 0.5}, options={"add_inputs": False}, psbt_version=2)["psbt"] + original = hww.decodepsbt(psbt) + assert_equal(original["input_count"], 1) + + # PSBT v2 merging ignores sequence differences when identifying + # the transaction, but must preserve the original sequence. A + # signature for the changed transaction cannot complete it. + for mode in ["change_sequence", "corrupt_signature"]: + self.set_mock_sign_mode(self.nodes[1], mode) + res = hww.walletprocesspsbt(psbt) + assert_equal(res["complete"], False) + assert "hex" not in res + decoded = hww.decodepsbt(res["psbt"]) + for key in ["tx_version", "fallback_locktime", "input_count", "output_count", "outputs"]: + assert_equal(decoded[key], original[key]) + for key in ["previous_txid", "previous_vout", "sequence"]: + assert_equal(decoded["inputs"][0][key], original["inputs"][0][key]) + + self.clear_mock_sign_mode(self.nodes[1]) + res = hww.walletprocesspsbt(psbt) + assert res["complete"] + assert hww.testmempoolaccept([res["hex"]])[0]["allowed"] + def test_disconnected_signer(self): self.log.info('Test disconnected external signer') From 27961808424345b112a2bca59457c9de54782fba Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Mon, 28 Sep 2026 07:48:39 +0000 Subject: [PATCH 06/13] external_signer: reject finalized PSBT inputs Require signer responses to keep signatures in non-final fields and leave finalization to Bitcoin Core. Document the requirement in the signer API. Test final scriptSig and witness fields independently, including responses that finalize only one input. --- doc/external-signer.md | 2 ++ src/external_signer.cpp | 5 +++++ test/functional/mocks/signer.py | 11 +++++++++++ test/functional/wallet_signer.py | 21 +++++++++++++++++++++ 4 files changed, 39 insertions(+) diff --git a/doc/external-signer.md b/doc/external-signer.md index 1e6ffb528bda..d125fba87b85 100644 --- a/doc/external-signer.md +++ b/doc/external-signer.md @@ -150,6 +150,8 @@ This command reads request `` and MUST return a JSON object The returned PSBT MUST use the same PSBT version as the request. +The returned PSBT MUST NOT contain finalized inputs (`PSBT_IN_FINAL_SCRIPTSIG` or `PSBT_IN_FINAL_SCRIPTWITNESS`). Signatures MUST remain in the partial signature or Taproot signature fields. + PSBT SHOULD include BIP32 derivations. The command SHOULD fail if none of the BIP32 derivations match a key owned by the device. The command SHOULD fail if the user cancels. diff --git a/src/external_signer.cpp b/src/external_signer.cpp index b4646e43e4df..d4d373a26273 100644 --- a/src/external_signer.cpp +++ b/src/external_signer.cpp @@ -126,6 +126,11 @@ bool ExternalSigner::SignTransaction(PartiallySignedTransaction& psbtx, std::str return false; } + if (std::ranges::any_of(signer_psbtx->inputs, PSBTInputSigned)) { + error = "Signer returned a PSBT with finalized inputs"; + return false; + } + if (!psbtx.Merge(*signer_psbtx)) { error = "Signer returned a PSBT for a different transaction"; return false; diff --git a/test/functional/mocks/signer.py b/test/functional/mocks/signer.py index e4f53f168f25..90c121d6f683 100755 --- a/test/functional/mocks/signer.py +++ b/test/functional/mocks/signer.py @@ -154,6 +154,17 @@ def signtx(args): if key == PSBT_IN_TAP_KEY_SIG or (isinstance(key, bytes) and key[0] == PSBT_IN_PARTIAL_SIG): stripped_in.map[key] = value reply = stripped.to_base64() + elif mode in ("finalized", "partially_finalized"): + finalized = wallet.finalizepsbt(reply, extract=False) + assert finalized["complete"] + if mode == "finalized": + reply = finalized["psbt"] + else: + # Finalize only one input, leaving the rest unfinalized. + signed = PSBT.from_base64(reply) + assert len(signed.i) > 1 + signed.i[0] = PSBT.from_base64(finalized["psbt"]).i[0] + reply = signed.to_base64() elif mode == "corrupt_signature": signed = PSBT.from_base64(reply) for psbt_in in signed.i: diff --git a/test/functional/wallet_signer.py b/test/functional/wallet_signer.py index 6b8982df47af..ae6488797456 100755 --- a/test/functional/wallet_signer.py +++ b/test/functional/wallet_signer.py @@ -89,6 +89,7 @@ def run_test(self): self.test_signer_stripped_psbt() self.test_misbehaving_signer() self.test_invalid_signer_signatures() + self.test_finalized_signer() self.test_disconnected_signer() self.restart_node(1, [f"-signer={self.mock_invalid_signer_path()}", "-keypool=10"]) self.test_invalid_signer() @@ -300,6 +301,26 @@ def test_invalid_signer_signatures(self): assert res["complete"] assert hww.testmempoolaccept([res["hex"]])[0]["allowed"] + def test_finalized_signer(self): + hww = self.nodes[1].get_wallet_rpc('hww') + # Exercise final_script_sig and final_script_witness independently. + for address_type in ["legacy", "bech32m"]: + self.log.info(f'Test finalized signer inputs for {address_type}') + addresses = [hww.getnewaddress(address_type=address_type) for _ in range(2)] + inputs = self.create_outpoints(self.nodes[0], outputs=[{address: 1} for address in addresses]) + self.generate(self.nodes[0], 1, sync_fun=self.sync_except_mock) + dest = self.nodes[0].getnewaddress() + + for mode in ["finalized", "partially_finalized"]: + self.set_mock_sign_mode(self.nodes[1], mode) + with self.nodes[1].assert_debug_log(["Signer returned a PSBT with finalized inputs"]): + assert_raises_rpc_error(-25, "External signer failed to sign", hww.send, outputs={dest: 1.5}, inputs=inputs, add_inputs=False) + + self.clear_mock_sign_mode(self.nodes[1]) + res = hww.send(outputs={dest: 1.5}, inputs=inputs, add_inputs=False, add_to_wallet=False) + assert res["complete"] + assert hww.testmempoolaccept([res["hex"]])[0]["allowed"] + def test_disconnected_signer(self): self.log.info('Test disconnected external signer') From 4110fbd0570711ba7cb780eb4d2b6088364e266a Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Sat, 24 Oct 2026 05:58:11 +0000 Subject: [PATCH 07/13] external_signer: reject unsafe sighash types A signature with SIGHASH_NONE or SIGHASH_SINGLE doesn't commit to all outputs, letting anyone alter them after signing. Reject a PSBT from an external signer that declares such a sighash type or contains signatures made with one. SIGHASH_ANYONECANPAY is still accepted: it only permits adding inputs, which does not affect us. The mock signer produces real signatures for these scenarios by letting its wallet sign with the requested sighash type, optionally hiding the declared sighash type field so that only the signatures themselves reveal it. Co-authored-by: brunoerg --- doc/external-signer.md | 2 +- src/external_signer.cpp | 37 ++++++++++++++++++++++++++++++++ test/functional/mocks/signer.py | 26 +++++++++++++++++++++- test/functional/wallet_signer.py | 31 ++++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 2 deletions(-) diff --git a/doc/external-signer.md b/doc/external-signer.md index d125fba87b85..0a2158eece78 100644 --- a/doc/external-signer.md +++ b/doc/external-signer.md @@ -150,7 +150,7 @@ This command reads request `` and MUST return a JSON object The returned PSBT MUST use the same PSBT version as the request. -The returned PSBT MUST NOT contain finalized inputs (`PSBT_IN_FINAL_SCRIPTSIG` or `PSBT_IN_FINAL_SCRIPTWITNESS`). Signatures MUST remain in the partial signature or Taproot signature fields. +The returned PSBT MUST NOT contain finalized inputs (`PSBT_IN_FINAL_SCRIPTSIG` or `PSBT_IN_FINAL_SCRIPTWITNESS`). Signatures MUST remain in the partial signature or Taproot signature fields so Bitcoin Core can check their sighash types. PSBT SHOULD include BIP32 derivations. The command SHOULD fail if none of the BIP32 derivations match a key owned by the device. diff --git a/src/external_signer.cpp b/src/external_signer.cpp index d4d373a26273..4ce2505c41be 100644 --- a/src/external_signer.cpp +++ b/src/external_signer.cpp @@ -8,10 +8,13 @@ #include #include #include +#include