Skip to content

wallet: fix crash when external signer wallet creation fails - #36767

Open
zerog975 wants to merge 3 commits into
bitcoin:masterfrom
zerog975:u3-createwallet-signer-error
Open

zerog975 wants to merge 3 commits into
bitcoin:masterfrom
zerog975:u3-createwallet-signer-error

Conversation

@zerog975

@zerog975 zerog975 commented Nov 5, 2026 •

Copy link
Copy Markdown

When testing a hardware wallet integration, I found that when attempting to create a wallet with the wrong app open on the hardware wallet, the GUI crashes instead of showing an error message. After restarting, when attempting to create a wallet with the same name again, it fails with "Database already exists". Over RPC, there's no crash, but createwallet returns error code -1 and leaves the same files and directories behind.

This happens when setting up an external-signer wallet. When the signer fails, setting up the wallet throws std::runtime_error, and CreateWallet() doesn't catch it. The GUI's worker thread has no handler, so the uncaught exception ends in std::terminate, and RPC's catch-all turns it into error code -1. The directory and wallet.dat are created before setup and never removed when setup fails.

This uncaught exception has been encountered previously in bitcoin-core/gui#395, and bitcoin-core/gui#396 stopped the dialog from enabling the "External signer" option, but didn't handle the exception.

Commit 1 catches the exception as LoadWalletInternal() does. The GUI shows an error dialog, and RPC returns error code -4, with the message starting with "Wallet creation failed."
Commit 2 ensures that on failure, it removes only what was created. It checks what exists with fs::symlink_status(), as MakeDatabase() does, so a wallet.dat symlink is kept even if its target doesn't exist, and it logs a warning when a removal fails. The cleanup also runs for failures that don't throw, e.g. an invalid -addresstype.
Commit 3 adds a release note.

How to reproduce:

cmake -B build -DBUILD_GUI=ON && cmake --build build
build/bin/bitcoin-qt -regtest -datadir=$(mktemp -d) -signer="python3 test/functional/mocks/invalid_signer.py"

Then click File, Create Wallet, Create. "External signer" is already ticked and the name is pre-filled as trezor_t.

On master: terminate called after throwing an instance of 'std::runtime_error', the process aborts, and trezor_t/wallet.dat is left behind.
With the PR: a "Create wallet failed" dialog appears, a retry shows the same dialog, and nothing is left on disk.

The tests CreateWalletSignerFailure and CreateWalletInvalidArgs in wallet_tests create wallets through the wallet loader, which is the same call the GUI makes. wallet_signer.py now expects -4, and checks that a failed creation leaves nothing behind, that a retry fails the same way, and that a directory, files or a dangling wallet.dat symlink that already existed are kept; in the symlink case the database created at the link's target stays too, and the check is skipped on Windows, as in wallet_multiwallet.py. An empty wallet.dat that already existed is initialized by the attempt and kept, so the name is taken afterwards, as before this PR.

You can see the tests fail without the fix:

git checkout HEAD~3 -- src/wallet/wallet.cpp
cmake --build build
build/bin/test_bitcoin --run_test=wallet_tests/CreateWalletSignerFailure,CreateWalletInvalidArgs
build/test/functional/wallet_signer.py

@fanquake

fanquake commented Nov 6, 2026

Copy link
Copy Markdown
Member

cc @Sjors

@DrahtBot

DrahtBot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36990 (test: replace hard-coded RPC error codes by l0rinc)
  • #36897 (wallet, migration: Contain all legacy wallet and migration related things in its own subdirectory, namespace, and classes by achow101)
  • #36823 (wallet, migration: Skip legacy wallet records rather than erasing them, and drop unused record erase functions by achow101)
  • #33112 (wallet: relax external_signer flag constraints by Sjors)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

Setting up an external signer wallet throws std::runtime_error when the
signer fails, for example when it returns an invalid descriptor.
CreateWallet() didn't catch it. Over RPC this became a generic -1
error, but the GUI creates wallets on a worker thread with no handler,
so bitcoin-qt aborted.

Catch std::runtime_error around CWallet::CreateNew(), as
LoadWalletInternal() does when loading, and report it as a normal
creation failure. bitcoin-qt now shows its "Create wallet failed"
dialog, and createwallet returns RPC_WALLET_ERROR (-4) instead of -1.

Update the affected wallet_signer.py error codes, and add a unit test
that creates the wallet through the wallet loader, as the GUI does.
@zerog975
zerog975 force-pushed the u3-createwallet-signer-error branch from 884aae1 to ab02999 Compare November 6, 2026 17:13
@zerog975

zerog975 commented Nov 6, 2026

Copy link
Copy Markdown
Author

Rebased on master, no changes to the commits. The "test ancestor commits" job merges master into each commit before building, so with the old workflow file in this branch it configured master's code with clang 18 and failed the clang 19 check that #36036 added; the rebase picks up the runner change from that PR.

CreateWallet() creates the wallet directory and its database
(wallet.dat) before setting up the wallet. If setup then fails, they
are left behind and the name can't be used again: the next attempt
fails with "Database already exists". This happens for any setup
failure, over RPC as well as in the GUI.

Note what exists before the database is created. On failure, remove
the database files only if wallet.dat is new, and the directory only
if it is new and empty, as RestoreWallet() does. Check what exists
with fs::symlink_status(), as MakeDatabase() does, so that a
wallet.dat symlink counts as existing even if its target doesn't;
otherwise the cleanup would delete the user's link and leave the
database at its target. A path that can't be checked also counts as
existing. Use the non-throwing overloads, as the GUI does not catch
exceptions here, and log a warning when a removal fails.

Extend the unit test to retry the same name, add one for a failure
that doesn't throw, and check in wallet_signer.py that a directory and
files that already existed are kept. An empty wallet.dat that existed
before is initialized by the attempt and kept, so the name is taken
afterwards, as before this change; a dangling wallet.dat symlink is
kept together with the database created at its target. The symlink
case is skipped on Windows, as in wallet_multiwallet.py.
@zerog975
zerog975 force-pushed the u3-createwallet-signer-error branch from ab02999 to edc9114 Compare November 8, 2026 21:10
@zerog975

zerog975 commented Nov 8, 2026

Copy link
Copy Markdown
Author

Pushed changes for the points raised in the automated Ralph review linked above, and added a release note.

  • The existence checks before the database is created now use fs::symlink_status(), as MakeDatabase() does. A wallet.dat symlink whose target doesn't exist counted as absent before, so the cleanup deleted the link and left the new database at its target; now both are kept. wallet_signer.py covers this, skipped on Windows like the symlink checks in wallet_multiwallet.py.
  • A removal that fails is logged.
  • The test also checks that a wallet.dat that already existed is initialized by the failed attempt and kept, so the name is taken afterwards, as before.
  • New third commit with doc/release-notes-36767.md. The "fail without the fix" snippet in the description is now HEAD~3.

Not changed: the first finding, that a loadwallet of the same name (or of a symlink alias) could open the database between its close and the removal. RestoreWallet() has the same window, and on master the partial database is left behind permanently.

@Sjors

Sjors commented Nov 12, 2026

Copy link
Copy Markdown
Member

This happens when setting up an external-signer wallet. When the signer fails, setting up the wallet throws std::runtime_error, and CreateWallet() doesn't catch it.

Catching the CWallet::CreateNew exception makes sense, but I think it's better to catch it inside that function.

@DrahtBot DrahtBot added Wallet and removed CI failed labels Nov 12, 2026
@maflcko

maflcko commented Nov 12, 2026

Copy link
Copy Markdown
Member

I think the issue is more broad than that? When looking at the external signer code, it seem it mixes error handling via results and exceptions, but the exceptions are never handled? E.g. the enumeratesigners RPC has a catch, but the other RPCs do not. Also the PSBT flows are inconsistent, which seems like the GUI would crash there as well?

So for the RPC I created this patch, not saying it should be taken, but I wanted to highlight the general issues.
From fab40b01a704126a424b7b1560e08a545d62857d Mon Sep 17 00:00:00 2001
From: MarcoFalke <*~=`'#}+{/-|&$^[email protected]>
Date: Tue, 10 Nov 2026 14:21:46 +0100
Subject: [PATCH] rpc: Handle external signer runtime errors explicitly

Just like enumeratesigners, translate to RPC_MISC_ERROR in createwallet
and walletdisplayaddress as well.

Also, when handling PSBTs with the external signer, return
EXTERNAL_SIGNER_FAILED like for other signer errors.
---
 src/rpc/external_signer.cpp                   |  4 ++--
 .../external_signer_scriptpubkeyman.cpp       | 23 +++++++++++--------
 src/wallet/rpc/addresses.cpp                  | 10 ++++++--
 src/wallet/rpc/wallet.cpp                     |  8 ++++++-
 4 files changed, 31 insertions(+), 14 deletions(-)

diff --git a/src/rpc/external_signer.cpp b/src/rpc/external_signer.cpp
index 8e7af284a40c..ab513d2eb455 100644
--- a/src/rpc/external_signer.cpp
+++ b/src/rpc/external_signer.cpp
@@ -14,7 +14,7 @@
 #include <rpc/util.h>
 #include <univalue.h>
 
-#include <exception>
+#include <stdexcept>
 #include <string>
 #include <utility>
 #include <vector>
@@ -59,7 +59,7 @@ static RPCMethod enumeratesigners()
                     signer_res.pushKV("name", signer.m_name);
                     signers_res.push_back(std::move(signer_res));
                 }
-            } catch (const std::exception& e) {
+            } catch (const std::runtime_error& e) { // for external signer errors
                 throw JSONRPCError(RPC_MISC_ERROR, e.what());
             }
             UniValue result(UniValue::VOBJ);
diff --git a/src/wallet/external_signer_scriptpubkeyman.cpp b/src/wallet/external_signer_scriptpubkeyman.cpp
index 96f1ee6cfcc0..a0536dac3fff 100644
--- a/src/wallet/external_signer_scriptpubkeyman.cpp
+++ b/src/wallet/external_signer_scriptpubkeyman.cpp
@@ -98,15 +98,20 @@ std::optional<PSBTError> ExternalSignerScriptPubKeyMan::FillPSBT(PartiallySigned
     }
     if (complete) return {};
 
-    auto signer{GetExternalSigner()};
-    if (!signer) {
-        LogWarning("%s", util::ErrorString(signer).original);
-        return PSBTError::EXTERNAL_SIGNER_NOT_FOUND;
-    }
-
-    std::string failure_reason;
-    if(!signer->SignTransaction(psbt, failure_reason)) {
-        LogWarning("Failed to sign: %s\n", failure_reason);
+    try {
+        auto signer{GetExternalSigner()};
+        if (!signer) {
+            LogWarning("%s", util::ErrorString(signer).original);
+            return PSBTError::EXTERNAL_SIGNER_NOT_FOUND;
+        }
+
+        std::string failure_reason;
+        if (!signer->SignTransaction(psbt, failure_reason)) {
+            LogWarning("Failed to sign: %s", failure_reason);
+            return PSBTError::EXTERNAL_SIGNER_FAILED;
+        }
+    } catch (const std::runtime_error& e) {
+        LogWarning("Failed to sign: %s", e.what());
         return PSBTError::EXTERNAL_SIGNER_FAILED;
     }
     if (options.finalize) FinalizePSBT(psbt); // This won't work in a multisig setup
diff --git a/src/wallet/rpc/addresses.cpp b/src/wallet/rpc/addresses.cpp
index 96dc9484293f..6192a81fd702 100644
--- a/src/wallet/rpc/addresses.cpp
+++ b/src/wallet/rpc/addresses.cpp
@@ -17,6 +17,8 @@
 
 #include <univalue.h>
 
+#include <stdexcept>
+
 namespace wallet {
 RPCMethod getnewaddress()
 {
@@ -707,8 +709,12 @@ RPCMethod walletdisplayaddress()
                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
             }
 
-            util::Result<void> res = pwallet->DisplayAddress(dest);
-            if (!res) throw JSONRPCError(RPC_MISC_ERROR, util::ErrorString(res).original);
+            try {
+                util::Result<void> res = pwallet->DisplayAddress(dest);
+                if (!res) throw JSONRPCError(RPC_MISC_ERROR, util::ErrorString(res).original);
+            } catch (const std::runtime_error& e) { // for external signer errors
+                throw JSONRPCError(RPC_MISC_ERROR, e.what());
+            }
 
             UniValue result(UniValue::VOBJ);
             result.pushKV("address", request.params[0].get_str());
diff --git a/src/wallet/rpc/wallet.cpp b/src/wallet/rpc/wallet.cpp
index 3983776b5a71..245ece635c2c 100644
--- a/src/wallet/rpc/wallet.cpp
+++ b/src/wallet/rpc/wallet.cpp
@@ -26,6 +26,7 @@
 
 #include <algorithm>
 #include <optional>
+#include <stdexcept>
 #include <string_view>
 
 
@@ -429,7 +430,12 @@ static RPCMethod createwallet()
     options.create_passphrase = passphrase;
     bilingual_str error;
     std::optional<bool> load_on_start = request.params[6].isNull() ? std::nullopt : std::optional<bool>(request.params[6].get_bool());
-    const std::shared_ptr<CWallet> wallet = CreateWallet(context, request.params[0].get_str(), load_on_start, options, status, error, warnings);
+    std::shared_ptr<CWallet> wallet;
+    try {
+        wallet = CreateWallet(context, request.params[0].get_str(), load_on_start, options, status, error, warnings);
+    } catch (const std::runtime_error& e) { // for external signer errors
+        throw JSONRPCError(RPC_MISC_ERROR, e.what());
+    }
     HandleWalletError(wallet, status, error);
 
     UniValue obj(UniValue::VOBJ);

@maflcko

maflcko commented Nov 12, 2026

Copy link
Copy Markdown
Member

Also @zerog975 : LLM output is not accepted if the author can not properly explain, test or could have written the change themselves. Also, LLM generated content is not allowed in comments/communications. See https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants