Skip to content

qt: keep Encrypt Wallet responsive during existing-wallet encryption - #178

Merged
kiwidream merged 4 commits into
1.x.xfrom
kiwidream/async-encrypt-wallet
Sep 25, 2026
Merged

kiwidream merged 4 commits into
1.x.xfrom
kiwidream/async-encrypt-wallet

Conversation

@kiwidream

@kiwidream kiwidream commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Encrypting an existing wallet from qbit-qt called CWallet::EncryptWallet on the GUI thread, so the window froze until encryption finished (about 20 s for a populated testnet wallet in the #174 inspection). This moves the encryption to a worker thread and keeps the GUI responsive, without changing the encryption itself.

  • Worker. WalletModel::encryptWallet runs the wallet's encryption on a QThread. It uses the same pattern as the fee-bump worker: a cloned interfaces::Wallet, a QPointer plus generation guard, and a join in ~WalletModel. The result is posted back through encryptWalletFinished. Encryption can't be cancelled; unload and shutdown wait for it to finish.

  • Dialog. AskPassphraseDialog stays open as a busy indicator (indeterminate progress bar) and ignores reject, close, Escape and a second submit while encryption runs. It then shows the existing success or failure message.

  • No GUI reads that block on the wallet lock. EncryptWallet holds the wallet lock for most of the operation, so the GUI must not query the wallet while it runs:

    • getEncryptionStatus() and getPQCKeyValidationInfo() return values captured before the worker started.
    • updateWalletStatus skips the HD-status query.
    • Status and canGetAddresses notifications raised under the lock are delivered once the worker returns.
    • requestUnlock and bumpFee are refused while encryption runs.
    • Payment requests (qbit: URIs) are queued until it finishes.

    This also covers another loaded wallet's status changes, which route through the current wallet's model.

  • Failure outcomes. A clean false return still reports "Your wallet was not encrypted". An exception is different, because the wallet can throw after it has already written the encryption to the database. The exception is captured on the worker and rethrown on the GUI thread. It reaches the same GuiMain runaway-exception handler as when encryption ran synchronously, and that handler stops the app. The user is never told a possibly committed encryption did not happen.

There are no wallet, interface, consensus, RPC or format changes; everything is in src/qt. The Create Wallet dialog's encryption path is unchanged.

Fixes #172.

Testing

  • Built locally.
  • Ran focused unit or functional tests for the changed area.
  • Ran lint or formatting checks relevant to this change.
  • Not run. Reason:

Linux x86_64, GCC 15.2, RelWithDebInfo, QT_QPA_PLATFORM=offscreen.

New WalletTests cases, most using a synthetic wallet whose encryption can be held open:

  • The event loop keeps running during encryption, checked by a stall watchdog.
  • Double submit is rejected, and the deferred notifications are delivered.
  • The clean-failure path shows "not encrypted".
  • A model destroyed mid-encryption closes the dialog without a status refresh.
  • A second wallet's status change during encryption does not block.
  • An exception escapes the event loop instead of being reported as "not encrypted".
  • A real funded descriptor wallet ends encrypted and locked, and after reopening from a copy of its database its history, address book, unlock, send and relock all work.

Commands and results:

  • build/bin/test_qbit-qt: every suite passes. Two independent builds ran it 3 and 2 times respectively.
  • test_qbit --run_test=wallet_tests passes, and functional wallet_encryption.py and wallet_keypool.py pass.
  • The new tests fail against the old code:
    • With the production files at base c4b254e2, the suite fails with "GUI thread stopped processing events while the wallet was being encrypted". It does not hang.
    • With only the follow-up commit's production changes reverted, the two-wallet freeze, exception and finished() assertions fail.
  • An independent adversarial review found the multi-wallet freeze and the exception misreporting; both are fixed here.

Not verified:

Target Branch

  • This PR targets main or a maintainer-requested release branch such as 0.1.x.

Targets 1.x.x for v1.0.1 (#174). It touches walletmodel.h next to #177; whichever merges second needs a small conflict resolution.

Risk / Review Notes

  • Consensus, script, crypto, wallet, P2P, release, CI, or security-sensitive behavior changed.
  • No consensus, script, crypto, wallet, P2P, release, CI, or security-sensitive behavior changed.

Notes: this changes threading around an irreversible wallet operation. The wallet's own encryption logic is untouched. Three races already exist in CWallet::EncryptWallet and are out of scope here:

  • IsCrypted() is checked before LOCK2, so an encryptwallet RPC overlapping the GUI worker could double-encrypt and hit an assert.
  • mapMasterKeys stays populated if TxnBegin fails.
  • IsHDEnabled and GetActiveScriptPubKeyMans read the SPKM maps without cs_wallet.

They are worth a separate issue.

Docs / Process Impact

Choose exactly one:

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

kiwidream and others added 2 commits September 24, 2026 11:26
AskPassphraseDialog called WalletModel::setWalletEncrypted from the GUI
thread, and CWallet::EncryptWallet holds the wallet locks while it
encrypts the keys, generates the new descriptors and keypools and
rewrites the database. A populated wallet froze qbit-qt for the whole
operation, so a successful encryption looked like a hung application.

Run the encryption on a worker thread, following the fee-bump worker in
WalletModel: the worker owns a cloned wallet interface, releases the
passphrase and the clone on its own thread, and posts the outcome to the
model through a QPointer and a generation guard. The passphrase dialog
stays open as the non-cancellable progress indicator (busy bar, disabled
buttons, reject/close ignored) until encryptWalletFinished() delivers the
result, then shows the existing success or failure message.

The wallet notifies status and keypool changes from inside the
encryption while it still holds its locks; a listener reading the wallet
on the GUI thread would block on them. Hold those notifications back
while the worker runs and deliver them once it has returned, and skip
the tip-driven PQC status refresh in BitcoinGUI for the same reason.
requestUnlock() and bumpFee() are refused while an encryption is active,
and a second encryptWallet() call starts nothing. ~WalletModel joins the
worker, so wallet unload and application shutdown complete the
encryption before touching the model.

Wallet-layer behaviour is unchanged: the single database transaction,
the rewrite, the key and PQC counter semantics and the encrypted,
locked end state are exactly what the synchronous call produced.

The synthetic test wallet gains an encryption latch that blocks lock-
dependent calls while it is held, so a GUI-thread call into the wallet
during encryption stalls the test the way it stalls the application.
New WalletTests cover the responsive event loop with deferred
notifications, dialog double-submit and dismissal, refused unlock and
fee bump, the failure path, model destruction while encrypting, and a
real funded descriptor wallet that ends encrypted and locked with its
history and address book intact and its keys usable through an
unlock, spend and relock. Against the synchronous implementation the
suite fails at the responsiveness assertion.

Fixes #172

Co-Authored-By: Claude <[email protected]>
Follow-up to the Encrypt Wallet worker: review found two ways the GUI
thread could still reach the wallet while the worker holds its locks,
and one way an exception from the wallet was misreported.

BitcoinGUI::updateWalletStatus runs for every wallet's status change and
reads the current wallet, so another wallet's PQC validation step or
relock during an encryption blocked the GUI thread in CWallet::IsLocked.
Have WalletModel::getEncryptionStatus() and getPQCKeyValidationInfo()
answer from the values taken before the worker started while it runs,
so one guard covers every caller, and drop the narrower guard in
updateWalletPQCValidationStatus. The HD status query in
updateWalletStatus reads the descriptor managers the worker replaces;
skip it until the model refreshes the status on completion. A payment
URI received during the encryption fills in the Send page from the
address book under the same lock; deliver it once the encryption has
finished.

CWallet::EncryptWallet can throw after its database transaction has
committed, from the descriptor setup or the database rewrite. The
worker reported that as success=false and the dialog told the user the
wallet was not encrypted, while the master key was already on disk and
the keys were half encrypted in memory. Carry the exception to the GUI
thread and rethrow it there, so it escapes into the application's
runaway-exception handler and ends the process the way the synchronous
call did; the wallet reloads from what was committed. A clean false
return still reports the failure as before.

When the model is destroyed mid-encryption, the dialog now closes
without done(), because its finished() listeners refresh the wallet
status from the dying model. The null-model check after the
confirmation guarded against an unload that is deferred while a modal
dialog is open; it is an assertion again.

Tests: the synthetic wallet reports itself encrypted from the start of
the operation, as the real wallet does once the master key is stored,
and can throw after its latch is released. New WalletTests cover a
second wallet's status change during encryption and the exception path,
the destroyed-model test checks that finished() is not emitted, and the
real-wallet test reopens the wallet from its records and checks it is
encrypted, locked, still has its history and address book, and unlocks
with the passphrase. Without the model and GUI changes the suite fails
the new assertions without hanging.

Fixes #172

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-25T17:05:03.044393Z 0bf19d1 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 83f0aa9379

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/qt/walletmodel.cpp Resolved
TransactionTableModel::updateTransaction() arrives through the event
loop and, for a new transaction, reads it from the wallet under
cs_wallet. With the encryption running on a worker thread the loop is
responsive, so a notification queued as the encryption started was
dispatched while the worker held the lock and blocked the GUI thread
until the encryption finished.

Hold such updates back in the table model while
WalletModel::isEncryptingWallet() and replay them in arrival order from
finishEncryptWallet() after the worker has released the wallet, before
encryptWalletFinished() shows the result. setProcessingQueuedTransactions()
is held back the same way so the balloon limit keeps bracketing the
updates it was queued around.

The synthetic test wallet now waits on its encryption latch in the
transaction reads that take cs_wallet in the real wallet, records the
transaction-changed listeners, and can hold one transaction. The new
WalletTests case raises a CT_NEW notification while the encryption is
held open and checks that the GUI thread keeps servicing events and
that the row appears once the encryption finishes; against the previous
implementation it fails at the watchdog assertion.

Fixes #172

Co-Authored-By: Claude <[email protected]>
@kiwidream

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 1312189350

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@kiwidream kiwidream closed this Sep 24, 2026
@kiwidream kiwidream reopened this Sep 24, 2026
Clang's -Wthread-safety-precise cannot match the lambda's
EXCLUSIVE_LOCKS_REQUIRED(w.cs_wallet) to the caller's
WITH_LOCK(wallet->cs_wallet, ...), so the thread-safety CI builds failed
with -Werror in TestEncryptWalletRealWallet. Lock inside the helper
instead; the test checks the same thing.

Refs #172

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kiwidream
kiwidream merged commit a32081e into 1.x.x Sep 25, 2026
37 checks passed
kiwidream added a commit that referenced this pull request Sep 28, 2026
* wallet: close races around CWallet::EncryptWallet

EncryptWallet decided whether the wallet could be encrypted before it
took the wallet locks, and the key derivation that follows is tuned to
take a noticeable amount of time. A second EncryptWallet caller in that
window, such as the encryptwallet RPC overlapping the GUI worker added
by #178, passed the same check, encrypted the already encrypted keys
and hit the assert in the encryption loop.

Move the already-encrypted and PQC-validation checks under the wallet
locks, after the key derivation. The derivation still runs unlocked so
it does not stall other wallet users, while the check and the
encryption now happen under one lock acquisition, so the losing caller
returns false without touching the wallet. The encryptwallet RPC takes
the same locks before its own already-encrypted check, so an
overlapping RPC call reports the wallet as already encrypted once the
other encryption has finished, instead of a generic failure.

The new master key was inserted into mapMasterKeys before the database
transaction began, so a failed TxnBegin left the wallet reporting
IsCrypted() with nothing written. Insert it only once the transaction
is open and the master key record has been written; a failed write
aborts the transaction. Post-commit failures are unchanged.

IsHDEnabled and GetActiveScriptPubKeyMans read the active manager maps
without cs_wallet, which EncryptWallet replaces under the lock.
GetActiveScriptPubKeyMans, IsActiveScriptPubKeyMan and
ConnectScriptPubKeyManNotifiers now require cs_wallet; IsHDEnabled and
the two callers that did not hold it take the lock.

A test hook parks one EncryptWallet caller between key derivation and
the locks while another completes. Further unit tests cover the failed
TxnBegin and the failed master key write, and wallet_encryption.py
runs two overlapping encryptwallet calls.

Fixes #179

Co-Authored-By: Claude <[email protected]>

* wallet: tighten EncryptWallet race follow-ups

When the encryptwallet RPC encrypts the wallet while the GUI's request is
under way, the GUI's request fails, but the wallet is encrypted with the
RPC's passphrase. The Encrypt Wallet dialog still reported that the
wallet was not encrypted. After a failed encryption the dialog now reads
the encryption status, which the model refreshes once the worker has
returned, and says the wallet was already encrypted by another request
and the entered passphrase was not used. A genuinely unencrypted wallet
keeps the existing message. The synthetic Qt wallet now refuses an
already encrypted wallet as CWallet::EncryptWallet does, and a Qt test
covers the new message.

ConcurrentEncryptWalletLoserFailsCleanly hung instead of failing when
the winning encryption's BOOST_REQUIRE failed: the loser's std::async
future was destroyed, and waited for the parked loser, before anything
released it. A scope guard declared after the future now releases the
loser on unwind.

The EncryptWallet comment said the key derivation does not stall other
wallet users, but the encryptwallet RPC holds the wallet locks for the
whole call; only callers that do not hold them, such as the GUI worker,
avoid the stall. Say so.

Fixes #179

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
kiwidream added a commit that referenced this pull request Sep 28, 2026
…on (#182)

* qt: answer address labels from the table model during wallet encryption

A repaint of the transaction list or the overview page resolves address
labels through AddressTableModel::labelForAddress, which asks the wallet
under cs_wallet. While the encryption worker from #178 holds the wallet
locks, an expose or repaint event stalled the GUI thread until the
encryption finished. No user input is needed: an uncomposited desktop
delivers one behind the application-modal passphrase dialog.

Every wallet read reachable from a paint path during an encryption goes
through that lookup: the ToAddress column's display, edit, tooltip and
foreground roles and the LabelRole and TxPlainTextRole answers in
TransactionTableModel, TxViewDelegate on the overview page and the
label search in TransactionFilterProxy. The other wallet reads in
data(), LongDescriptionRole and TxHexRole, need a user action the modal
dialog blocks; transaction status and balance polling already give up
with TRY_LOCK; the address book and recent-requests views answer from
their own rows, and the coin control view is rebuilt only by the user.

The address book cannot change while the worker holds the wallet, so
AddressTableModel::getAddressData answers from the rows it already holds
while WalletModel::isEncryptingWallet(), found by the encoded address
the rows are sorted on. One guard covers every caller of labelForAddress
and purposeForAddress, and outside an encryption the wallet is asked as
before.

The synthetic test wallet gains an address book and a status for the
transaction it holds, behind the encryption latch like the locks they
stand in for. The new WalletTests case repaints an OverviewPage and
requests every label-bearing role while the encryption is held open,
checks that the GUI thread keeps servicing events and that the labels
match before, during and after the encryption. Against the previous
implementation it fails at the watchdog assertion.

Fixes #180

Co-Authored-By: Claude <[email protected]>

* qt: cover P2MR, sending and refund rows in the encryption label test

The #180 test built its address book from one legacy receiving row, but
every release chain sets fRestrictedOutputMode, so the rows a production
wallet holds are P2MR bech32m addresses, and sending and hidden refund
rows go through the same lookup. A single row also left the search the
model answers from during an encryption with nothing to order.

The synthetic wallet now also pays a labelled P2MR receiving address and
files a P2MR sending and refund address, so the address book mixes both
encodings. The test checks the transaction list roles for the P2MR
payment and the label and purpose of every row before, during and after
the held encryption, which also covers mapping a row's type back to its
purpose. Against a32081e's address table model it still fails at the
watchdog assertion.

Fixes #180

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
kiwidream added a commit that referenced this pull request Oct 22, 2026
Add doc/release-notes-1.0.1.md covering every change merged to 1.x.x
since the signed v1.0.0 tag, grouped as #174 asks: wallet fixes, the
-fallbackfee default (#151), signing-usage visibility, validation and
performance work, release engineering, and known limitations.

The three pull requests #174 expects in the release that had not merged
when this was drafted (#176, #177, #178) are marked "pending merge", and
a Maintainer TODO section at the top lists what must be resolved before
the file is passed to the publisher: those markers, the exact P2MR v1
conformance sentence, the platform-signing disposition (#70), and the
fuzz evidence status (#173). No speedup is claimed for the signature
cache (#162) or descriptor batching (#163) because no measurement
accompanies the release.

The per-PR fragments doc/release-notes-150.md and doc/release-notes-151.md
are folded into the notes and left in place, as the v1.0.0 release did
with its fragments.

Refs #174

Co-Authored-By: Claude <[email protected]>
kiwidream added a commit that referenced this pull request Oct 22, 2026
#176, #177 and #178 merged into 1.x.x, so drop their pending-merge
markers. #182 and #183 merged after the notes were drafted; add them,
and call out #183's encryptwallet error-code change as a behavior
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 5, 2026
The Encrypt Wallet dialog runs the encryption on a worker thread and puts
WalletModel into a mode in which status, PQC validation and label reads
answer from cached values, and status, keypool and transaction-table
updates are held back (#178, #182). That mode engaged only when the GUI
started the encryption. The encryptwallet RPC holds the wallet locks for
the whole call while it generates the new keys, so it stalled the GUI
thread on those locks. On 2026-11-04, `qbit-cli encryptwallet` with
-keypool=3000 froze qbit-qt for about 200 seconds.

CWallet::EncryptWallet now counts itself in progress from its first line
until it returns or throws, whoever called it, and it raises
NotifyEncryptionInProgressChanged when it starts and when it ends. The
counter is an atomic that reads no wallet state, so the GUI can query it
without waiting for the locks. interfaces::Wallet exposes it as
isEncryptionInProgress() and handleEncryptionInProgressChanged(). The
announcement does not change the encryption itself: the #183 checks and
the #277 lock order are untouched, and an overlapping encryptwallet call
still returns -15 (RPC_WALLET_WRONG_ENC_STATE).

WalletModel::isEncryptingWallet() now also reports an encryption that the
wallet announces, so every guard from #178 and #182 covers it: the
encryption status, the PQC validation status, label lookups, status and
keypool notifications, transaction-table updates, the HD status in the
status bar, payment URIs, unlock requests and fee bumps. The model enters
this state the first time it sees the encryption and leaves it only when
it handles the wallet's notification that the encryption ended. Updates
held back in the meantime are therefore delivered before newer ones. The
notification is queued, and the model reads the in-progress state instead
of relying on the order in which notifications arrive, so a start that is
announced after the end cannot leave the model stuck.

When the encryption ends, the model refreshes the status from the wallet
whatever the outcome, including a failure, or an exception that skipped
the wallet's status notification. It then delivers what it held back and
emits the new walletEncryptionEnded() signal, which payment URIs now wait
for. The dialog's own result waits until every encryption in progress has
ended. If another encryption holds the wallet when the dialog's request is
refused, the dialog reports "already encrypted by another request" once
that encryption has finished, instead of reading the status from before
it.

The listener only posts a queued call and never waits for the GUI thread.
The notification can therefore be raised while the encryptwallet RPC holds
cs_wallet without deadlocking against a GUI-thread call that waits for
that lock. GUI actions that the user starts and that need the wallet, such
as creating a receiving address, still wait for an encryption started
outside the GUI, as in v1.0.0. The release notes list them.

The synthetic test wallet now announces its encryption. New WalletTests
start an encryption from another thread, as the RPC does, and hold it
open:

- The GUI thread keeps servicing events while the reads answer from the
  model, and the held-back updates are delivered once the encryption ends.
- A failure, an exception and a late start announcement each end the mode
  and refresh the status.
- A dialog request refused during another encryption reports the right
  result.
- Deleting the model, as unloading the wallet does, does not wait for the
  encryption.

A further test encrypts a real descriptor wallet with the wallet locks
held, as the RPC does, and parks it inside its database transaction. The
GUI stays responsive, a GUI-thread call that waits for cs_wallet completes
once the encryption has finished, and the model then reports the wallet as
encrypted and locked. Without the WalletModel changes, each new test fails
at its watchdog assertion.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 6, 2026
The Encrypt Wallet dialog runs the encryption on a worker thread and puts
WalletModel into a mode in which status, PQC validation and label reads
answer from cached values, and status, keypool and transaction-table
updates are held back (#178, #182). That mode engaged only when the GUI
started the encryption. The encryptwallet RPC holds the wallet locks for
the whole call while it generates the new keys, so it stalled the GUI
thread on those locks. On 2026-11-04, `qbit-cli encryptwallet` with
-keypool=3000 froze qbit-qt for about 200 seconds.

CWallet::EncryptWallet now counts itself in progress from its first line
until it returns or throws, whoever called it, and it raises
NotifyEncryptionInProgressChanged when it starts and when it ends. The
counter is an atomic that reads no wallet state, so the GUI can query it
without waiting for the locks. interfaces::Wallet exposes it as
isEncryptionInProgress() and handleEncryptionInProgressChanged(). The
announcement does not change the encryption itself: the #183 checks and
the #277 lock order are untouched, and an overlapping encryptwallet call
still returns -15 (RPC_WALLET_WRONG_ENC_STATE).

WalletModel::isEncryptingWallet() now also reports an encryption that the
wallet announces, so every guard from #178 and #182 covers it: the
encryption status, the PQC validation status, label lookups, status and
keypool notifications, transaction-table updates, the HD status in the
status bar, payment URIs, unlock requests and fee bumps. The model enters
this state the first time it sees the encryption and leaves it only when
it handles the wallet's notification that the encryption ended. Updates
held back in the meantime are therefore delivered before newer ones. The
notification is queued, and the model reads the in-progress state instead
of relying on the order in which notifications arrive, so a start that is
announced after the end cannot leave the model stuck.

When the encryption ends, the model refreshes the status from the wallet
whatever the outcome, including a failure, or an exception that skipped
the wallet's status notification. It then delivers what it held back and
emits the new walletEncryptionEnded() signal, which payment URIs now wait
for. The dialog's own result waits until every encryption in progress has
ended. If another encryption holds the wallet when the dialog's request is
refused, the dialog reports "already encrypted by another request" once
that encryption has finished, instead of reading the status from before
it.

The listener only posts a queued call and never waits for the GUI thread.
The notification can therefore be raised while the encryptwallet RPC holds
cs_wallet without deadlocking against a GUI-thread call that waits for
that lock. GUI actions that the user starts and that need the wallet, such
as creating a receiving address, still wait for an encryption started
outside the GUI, as in v1.0.0. The release notes list them.

The synthetic test wallet now announces its encryption. New WalletTests
start an encryption from another thread, as the RPC does, and hold it
open:

- The GUI thread keeps servicing events while the reads answer from the
  model, and the held-back updates are delivered once the encryption ends.
- A failure, an exception and a late start announcement each end the mode
  and refresh the status.
- A dialog request refused during another encryption reports the right
  result.
- Deleting the model, as unloading the wallet does, does not wait for the
  encryption.

A further test encrypts a real descriptor wallet with the wallet locks
held, as the RPC does, and parks it inside its database transaction. The
GUI stays responsive, a GUI-thread call that waits for cs_wallet completes
once the encryption has finished, and the model then reports the wallet as
encrypted and locked. Without the WalletModel changes, each new test fails
at its watchdog assertion.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 6, 2026
After rebasing onto 1.x.x, #344's AppTests timed out: it quits while
two PSBT dialogs, shown with ShowModalDialogAsynchronously(), are
signing, and expects the shutdown to hide them and keep their results.
IsUserInteractionPending() counted every visible modal widget, so the
quit waited for those dialogs indefinitely.

Defer shutdown and wallet unload only while a caller that would return
into the deleted wallet views is on the stack:
- a nested QEventLoop, as QDialog::exec() and QMenu::exec() run
  (loopLevel() > 1; every caller runs from the GUI thread's event loop);
- a native message box or file dialog, which runs the platform's modal
  loop instead (on macOS, [NSApp runModal]). In Qt 6.8, which depends
  pins (#347), QMessageBoxPrivate::setVisible() and
  QFileDialogPrivate::setVisible() call setNativeDialogVisible(), set
  WA_DontShowOnScreen and then call QDialogPrivate::setVisible(), so a
  visible modal widget with WA_DontShowOnScreen stands in for the native
  dialog. A Qt upgrade must re-check this. qbit sets the attribute
  nowhere else.

Qt dialogs shown without a loop of their own are on screen, have no
caller to return into, and no longer hold up a quit or an unload. The
wallet unload deferral uses the same rule, so unloadwallet is not
blocked by an open PSBT dialog.

Audit of asynchronously shown or non-exec dialogs that hold wallet
references, which 1.x.x's unload deferral had covered:
- CoinControlDialog had no parent but refers to its SendCoinsDialog's
  CCoinControl and WalletModel. An unload would delete both under it.
  Parent it to the SendCoinsDialog, so it is deleted with it.
- Safe: EditAddressDialog (address book page, transaction view),
  AskPassphraseDialog (encrypt, change passphrase),
  SignVerifyMessageDialog and ReceiveRequestDialog are children of the
  wallet view or its pages; PSBTOperationsDialog handles unload (#344);
  RPCConsole handles removeWallet; TransactionDescDialog copies its text
  and its view closes it; Options and About hold no wallet references;
  the wallet activity dialogs hold no loaded wallet; the fee-bump
  confirmation runs exec(); progress dialogs are unchanged.

Tests: an in-process check of the rule (runs without QProcess), and
quit-modal scenarios where a native-marked dialog defers quit and
unload, an open PSBT dialog does not hold an unload, and an unload
deletes an open Coin Control dialog. The encryption and PSBT signing
scenarios now expect the shutdown to start at once, with teardown
waiting for the work that cannot be cancelled. Each new or changed test
fails with the previous rule, without the Coin Control parent, or
without the native-dialog check. Native dialogs cannot be shown on
Linux CI, so the native path is tested through the attribute Qt sets.

Also update the comments that described the old rule (#178's in
AskPassphraseDialog::accept, #348's above
TestSendDestructionDuringConfirmation).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 9, 2026
The Encrypt Wallet dialog runs the encryption on a worker thread and puts
WalletModel into a mode in which status, PQC validation and label reads
answer from cached values, and status, keypool and transaction-table
updates are held back (#178, #182). That mode engaged only when the GUI
started the encryption. The encryptwallet RPC holds the wallet locks for
the whole call while it generates the new keys, so it stalled the GUI
thread on those locks. On 2026-11-04, `qbit-cli encryptwallet` with
-keypool=3000 froze qbit-qt for about 200 seconds.

CWallet::EncryptWallet now counts itself in progress from its first line
until it returns or throws, whoever called it, and it raises
NotifyEncryptionInProgressChanged when it starts and when it ends. The
counter is an atomic that reads no wallet state, so the GUI can query it
without waiting for the locks. interfaces::Wallet exposes it as
isEncryptionInProgress() and handleEncryptionInProgressChanged(). The
announcement does not change the encryption itself: the #183 checks and
the #277 lock order are untouched, and an overlapping encryptwallet call
still returns -15 (RPC_WALLET_WRONG_ENC_STATE).

WalletModel::isEncryptingWallet() now also reports an encryption that the
wallet announces, so every guard from #178 and #182 covers it: the
encryption status, the PQC validation status, label lookups, status and
keypool notifications, transaction-table updates, the HD status in the
status bar, payment URIs, unlock requests and fee bumps. The model enters
this state the first time it sees the encryption and leaves it only when
it handles the wallet's notification that the encryption ended. Updates
held back in the meantime are therefore delivered before newer ones. The
notification is queued, and the model reads the in-progress state instead
of relying on the order in which notifications arrive, so a start that is
announced after the end cannot leave the model stuck.

When the encryption ends, the model refreshes the status from the wallet
whatever the outcome, including a failure, or an exception that skipped
the wallet's status notification. It then delivers what it held back and
emits the new walletEncryptionEnded() signal, which payment URIs now wait
for. The dialog's own result waits until every encryption in progress has
ended. If another encryption holds the wallet when the dialog's request is
refused, the dialog reports "already encrypted by another request" once
that encryption has finished, instead of reading the status from before
it.

The listener only posts a queued call and never waits for the GUI thread.
The notification can therefore be raised while the encryptwallet RPC holds
cs_wallet without deadlocking against a GUI-thread call that waits for
that lock. GUI actions that the user starts and that need the wallet, such
as creating a receiving address, still wait for an encryption started
outside the GUI, as in v1.0.0. The release notes list them.

The synthetic test wallet now announces its encryption. New WalletTests
start an encryption from another thread, as the RPC does, and hold it
open:

- The GUI thread keeps servicing events while the reads answer from the
  model, and the held-back updates are delivered once the encryption ends.
- A failure, an exception and a late start announcement each end the mode
  and refresh the status.
- A dialog request refused during another encryption reports the right
  result.
- Deleting the model, as unloading the wallet does, does not wait for the
  encryption.

A further test encrypts a real descriptor wallet with the wallet locks
held, as the RPC does, and parks it inside its database transaction. The
GUI stays responsive, a GUI-thread call that waits for cs_wallet completes
once the encryption has finished, and the model then reports the wallet as
encrypted and locked. Without the WalletModel changes, each new test fails
at its watchdog assertion.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 10, 2026
* qt: wait for open dialogs before shutdown and wallet unload

BitcoinApplication::requestShutdown() deletes the wallet views. Two
quit requests reach it with no check for open dialogs: the platform's
Quit event (on macOS: Dock > Quit, logout or a Quit Apple event), and
File > Exit pressed through accessibility behind a dialog. Inside the
nested event loop of a dialog, the code after exec() then ran on freed
objects: SendCoinsDialog after the send confirmation, the "PSBT
copied" box or the PQC usage warning shown after a send, and the
passphrase prompt that WalletView keeps on its stack (#349).

Add GUIUtil::IsUserInteractionPending(). It returns true while a
nested event loop is on the stack or a modal dialog other than a
progress dialog is visible. The loop level also covers QMenu::exec(),
and a dialog that done() has already hidden but whose exec() has not
returned. Progress dialogs only report background work, which shutdown
cancels or waits for as before.

requestShutdown() now waits while that holds, retrying every
SHUTDOWN_POLLING_DELAY, and it shuts down only once. Before, a second
request, such as a second platform Quit, requested the node shutdown
again.

Wallet unload checked only the active modal widget. A progress dialog
on top of a dialog in exec(), such as a rescan's progress over the send
confirmation, let it delete the wallet view under that dialog. Unload
now uses the same rule and rechecks it on a timer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt, test: quit while a dialog is open

A process shuts its BitcoinApplication down only once, and AppTests
already uses that shutdown. QuitModalTests therefore runs each
scenario in a child process of test_qbit-qt that is selected through
QBIT_QT_TEST_QUIT_SCENARIO. Each child starts the application with a
synthetic wallet and requests a quit while a dialog is open. It checks
that the shutdown waits, then answers the dialog and checks that the
shutdown runs exactly once. A second platform Quit and File > Exit
during the node shutdown are then ignored.

- The platform Quit event and File > Exit inside the send confirmation,
  the "PSBT copied" box, the PQC usage warning after a send, and the
  passphrase prompt of a locked wallet. Nothing is sent or signed that
  the user did not confirm.
- A quit handled in the same event pass that closed the confirmation.
- A quit during wallet encryption and during PSBT signing after the
  counters were reserved (#174 C4). Both wait for the operation and for
  the user to close its dialog.
- A wallet unload while a rescan progress dialog covers the send
  confirmation.
- A quit with the console's command completer and a QMenu::popup() menu
  open, which must not wait.

Without the fix, the send-flow and unload scenarios abort under
AddressSanitizer with a heap-use-after-free or an invalid free, and the
others fail their checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: shut down once the main window exists and ignore a late init result

A platform Quit can arrive before GuiMain has created the main window,
for example during the Intro dialog. requestShutdown() deferred it while
the dialog was open. A retry in the pass that closed the dialog, at loop
level one, could still run it with no window and fail the assertion in
ShutdownWindow::showShutdownWindow(), as the quit did before at once.
It now also waits until the window exists.

A quit during initialization tears the GUI down and requests the node
shutdown, but initialization can still report success afterwards.
initializeResult() then created the client model and the wallet
controller and showed the window again. Before, the shutdown poll tore
those down a second time. Since requestShutdown() runs only once, they
would have stayed alive while the node unloaded its wallets.
initializeResult() now returns once the shutdown has started.

The run-once check in QuitModalTests now also asserts that it ran
before the node shutdown ended, and delivers a successful
initialization result at that point. A new scenario quits before the
main window exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* doc: name the quit-modal release note after #354

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: close an unloaded wallet's rescan progress and show what a quit waits for

WalletView::showProgress() creates its rescan progress dialog without a
parent, and ~WalletView left it open. When a wallet was unloaded under
that dialog, the dialog stayed visible and application-modal. The
shutdown poll, which runs only when no modal widget is active, then
ignored RPC stop and SIGTERM until the user cancelled the orphaned
dialog. ~WalletView now hides the dialog and deletes it later. The
destructor can run inside the dialog's own setValue(), which processes
events.

When requestShutdown() first defers a quit, it now shows the main
window if it is hidden or minimized, then raises and activates the
dialog that the quit waits for. A quit that seems to be ignored invites
a force quit, which skips the node's flush. It raises the dialog
directly: on Wayland, GUIUtil::bringToFront() re-creates the window,
and hiding a dialog ends its exec().

The release note now says that macOS cancels a logout started while
such a dialog is open, as it did before, and that qbit-qt quits once
the dialog is closed. It also notes that RPC stop and SIGTERM now wait
for an open context menu too.

QuitModalTests:
- The send-confirmation scenario checks that the deferred quit
  restores a minimized main window.
- A new unload-rescan-stop scenario unloads a wallet under its rescan
  progress dialog and stops the node.
- The latch that keeps a build without the fix from hanging starts its
  clock at the quit instead of at startup, with a 30 s limit, so slow
  hosts cannot fail the test spuriously.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt, test: skip the quit-modal scenarios when Qt lacks QProcess

The depends Qt for Linux is built with -no-feature-process, so <QProcess>
declares nothing there and the CentOS depends and i686 no-IPC GUI jobs
failed to compile quitmodaltests.cpp. Guard the child-process runner
with QT_CONFIG(process) and QSKIP the case otherwise, so it shows as
skipped instead of disappearing. Builds against a Qt with QProcess
(macOS, Windows, and Linux system-Qt jobs) still run every scenario.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: defer quit and unload only for nested and native dialog loops

After rebasing onto 1.x.x, #344's AppTests timed out: it quits while
two PSBT dialogs, shown with ShowModalDialogAsynchronously(), are
signing, and expects the shutdown to hide them and keep their results.
IsUserInteractionPending() counted every visible modal widget, so the
quit waited for those dialogs indefinitely.

Defer shutdown and wallet unload only while a caller that would return
into the deleted wallet views is on the stack:
- a nested QEventLoop, as QDialog::exec() and QMenu::exec() run
  (loopLevel() > 1; every caller runs from the GUI thread's event loop);
- a native message box or file dialog, which runs the platform's modal
  loop instead (on macOS, [NSApp runModal]). In Qt 6.8, which depends
  pins (#347), QMessageBoxPrivate::setVisible() and
  QFileDialogPrivate::setVisible() call setNativeDialogVisible(), set
  WA_DontShowOnScreen and then call QDialogPrivate::setVisible(), so a
  visible modal widget with WA_DontShowOnScreen stands in for the native
  dialog. A Qt upgrade must re-check this. qbit sets the attribute
  nowhere else.

Qt dialogs shown without a loop of their own are on screen, have no
caller to return into, and no longer hold up a quit or an unload. The
wallet unload deferral uses the same rule, so unloadwallet is not
blocked by an open PSBT dialog.

Audit of asynchronously shown or non-exec dialogs that hold wallet
references, which 1.x.x's unload deferral had covered:
- CoinControlDialog had no parent but refers to its SendCoinsDialog's
  CCoinControl and WalletModel. An unload would delete both under it.
  Parent it to the SendCoinsDialog, so it is deleted with it.
- Safe: EditAddressDialog (address book page, transaction view),
  AskPassphraseDialog (encrypt, change passphrase),
  SignVerifyMessageDialog and ReceiveRequestDialog are children of the
  wallet view or its pages; PSBTOperationsDialog handles unload (#344);
  RPCConsole handles removeWallet; TransactionDescDialog copies its text
  and its view closes it; Options and About hold no wallet references;
  the wallet activity dialogs hold no loaded wallet; the fee-bump
  confirmation runs exec(); progress dialogs are unchanged.

Tests: an in-process check of the rule (runs without QProcess), and
quit-modal scenarios where a native-marked dialog defers quit and
unload, an open PSBT dialog does not hold an unload, and an unload
deletes an open Coin Control dialog. The encryption and PSBT signing
scenarios now expect the shutdown to start at once, with teardown
waiting for the work that cannot be cancelled. Each new or changed test
fails with the previous rule, without the Coin Control parent, or
without the native-dialog check. Native dialogs cannot be shown on
Linux CI, so the native path is tested through the attribute Qt sets.

Also update the comments that described the old rule (#178's in
AskPassphraseDialog::accept, #348's above
TestSendDestructionDuringConfirmation).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: document the shutdown gates for quit and stop

The release note described the earlier rule. Correct it for the final
one:
- A platform or menu quit during wallet encryption or PSBT signing starts
  the shutdown at once; the shutdown waits for the work, and the "Wallet
  encrypted" box is not shown.
- The rules about dialogs apply to platform and menu quits only.
- RPC stop and SIGTERM keep upstream's rule: the GUI shuts down only while
  no modal dialog is open, including progress dialogs and dialogs such as
  the PSBT dialog.
- A second quit request is ignored, a quit during the first-run data
  directory dialog is carried out after startup, and most context menus
  hold a quit or stop until they close.

Add comments at the shutdown poll and at IsUserInteractionPending() that
explain why the two paths differ. No behavior change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 10, 2026
…it (#352)

* qt: keep the GUI responsive during wallet encryption started outside it

The Encrypt Wallet dialog runs the encryption on a worker thread and puts
WalletModel into a mode in which status, PQC validation and label reads
answer from cached values, and status, keypool and transaction-table
updates are held back (#178, #182). That mode engaged only when the GUI
started the encryption. The encryptwallet RPC holds the wallet locks for
the whole call while it generates the new keys, so it stalled the GUI
thread on those locks. On 2026-11-04, `qbit-cli encryptwallet` with
-keypool=3000 froze qbit-qt for about 200 seconds.

CWallet::EncryptWallet now counts itself in progress from its first line
until it returns or throws, whoever called it, and it raises
NotifyEncryptionInProgressChanged when it starts and when it ends. The
counter is an atomic that reads no wallet state, so the GUI can query it
without waiting for the locks. interfaces::Wallet exposes it as
isEncryptionInProgress() and handleEncryptionInProgressChanged(). The
announcement does not change the encryption itself: the #183 checks and
the #277 lock order are untouched, and an overlapping encryptwallet call
still returns -15 (RPC_WALLET_WRONG_ENC_STATE).

WalletModel::isEncryptingWallet() now also reports an encryption that the
wallet announces, so every guard from #178 and #182 covers it: the
encryption status, the PQC validation status, label lookups, status and
keypool notifications, transaction-table updates, the HD status in the
status bar, payment URIs, unlock requests and fee bumps. The model enters
this state the first time it sees the encryption and leaves it only when
it handles the wallet's notification that the encryption ended. Updates
held back in the meantime are therefore delivered before newer ones. The
notification is queued, and the model reads the in-progress state instead
of relying on the order in which notifications arrive, so a start that is
announced after the end cannot leave the model stuck.

When the encryption ends, the model refreshes the status from the wallet
whatever the outcome, including a failure, or an exception that skipped
the wallet's status notification. It then delivers what it held back and
emits the new walletEncryptionEnded() signal, which payment URIs now wait
for. The dialog's own result waits until every encryption in progress has
ended. If another encryption holds the wallet when the dialog's request is
refused, the dialog reports "already encrypted by another request" once
that encryption has finished, instead of reading the status from before
it.

The listener only posts a queued call and never waits for the GUI thread.
The notification can therefore be raised while the encryptwallet RPC holds
cs_wallet without deadlocking against a GUI-thread call that waits for
that lock. GUI actions that the user starts and that need the wallet, such
as creating a receiving address, still wait for an encryption started
outside the GUI, as in v1.0.0. The release notes list them.

The synthetic test wallet now announces its encryption. New WalletTests
start an encryption from another thread, as the RPC does, and hold it
open:

- The GUI thread keeps servicing events while the reads answer from the
  model, and the held-back updates are delivered once the encryption ends.
- A failure, an exception and a late start announcement each end the mode
  and refresh the status.
- A dialog request refused during another encryption reports the right
  result.
- Deleting the model, as unloading the wallet does, does not wait for the
  encryption.

A further test encrypts a real descriptor wallet with the wallet locks
held, as the RPC does, and parks it inside its database transaction. The
GUI stays responsive, a GUI-thread call that waits for cs_wallet completes
once the encryption has finished, and the model then reports the wallet as
encrypted and locked. Without the WalletModel changes, each new test fails
at its watchdog assertion.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* wallet: announce RPC encryption before taking the wallet locks

The encryptwallet RPC takes m_relock_mutex and cs_wallet before its
checks, and GetPQCKeyValidationInfo then waits for every descriptor
manager's cs_desc_man. A background P2MR refill or create-time top-up step
holds cs_desc_man without cs_wallet while it derives and writes keys, so
the RPC can sit with cs_wallet held before EncryptWallet raises the
in-progress counter. A GUI read in that window, such as a label lookup
during a repaint, waited for cs_wallet and so for the whole encryption:
the stall the previous commit fixes.

The counter and its notifications move into an RAII
CWallet::EncryptionInProgressScope. EncryptWallet holds one as before,
and the encryptwallet RPC now takes another before LOCK2. The counter
nests. The RPC's scope ends after the locks are released, so a call that
fails, or that finds the wallet encrypted and returns -15, also ends with
the GUI reading the wallet again. The scope does not touch the RPC's
checks or the lock order from #183 and #277.

A new WalletTests case runs the encryptwallet RPC against a real
descriptor wallet while a thread holds a descriptor manager's lock, the
way a keypool step does. The GUI keeps servicing events while the RPC
holds cs_wallet and waits for that lock, and the model answers from what
it last read. The encryption then completes, and a second call returns
-15 and still ends with walletEncryptionEnded(). Without the RPC's scope,
the test fails at its watchdog assertion.

The same test also covers an encryption that throws from
m_before_encrypt_wallet_locks: the announcement ends, and the model
reads the wallet again.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: refuse Encrypt Wallet while another encryption runs

While another caller, such as the encryptwallet RPC, was encrypting the
wallet, the GUI still showed it as unencrypted and accepted a request from
the Encrypt Wallet dialog. The worker then derived a key and waited for the
other encryption's locks. The dialog showed its progress bar for the rest
of that encryption, and only then reported that the wallet had been
encrypted by another request. Meanwhile ~WalletModel would have waited for
the worker.

WalletModel::encryptWallet() now refuses while isEncryptingWallet(), with
the "Wallet encryption in progress" message that unlock requests and fee
bumps get, and starts nothing. The dialog then closes without claiming a
result.

The dialog's own result still waits for every encryption in progress. The
encryptwallet RPC announces its encryption before it waits for the locks,
which can happen while the dialog's encryption holds them. The test that
covered this now exercises that order: the synthetic wallet can announce
an encryption without holding its latch, as the RPC does while it waits.
A new test covers the refusal and fails without it.

The release notes add opening a wallet in the GUI while it is being
encrypted to the known limitations: the model reads the wallet when it is
created.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: tighten the wallet-announced encryption mode

Follow-ups from a local review of this branch:

- The Encrypt Wallet dialog decided whether another encryption had
  refused its request by checking isEncryptingWallet() after the call.
  The model's "Wallet encryption in progress" message runs a nested event
  loop, which can see that other encryption end. The dialog then reported
  a result for an attempt the model never made. It now checks before
  asking, and WalletView refuses to open the dialog while another
  encryption runs, before the user has chosen a passphrase.
- WalletModel now reads the encryption and PQC validation status once it
  has subscribed to the wallet. A model that had not been asked for them
  before another caller started encrypting reported the defaults: an
  encrypted wallet showed as unencrypted while a refused encryptwallet
  call waited for the locks.
- encryptWallet() no longer resets the status the model last reported.
  Doing so could swallow an encryptionStatusChanged() whose notification
  was still queued. The getters now record the values that the GUI is
  answered from.
- Each encryption raises several notifications, and they can all be
  queued while the GUI thread is busy. The model now coalesces the
  refresh at the end of an encryption into one.
- If a listener threw from EncryptionInProgressScope's constructor, the
  announcement was rolled back without telling the listeners that had
  already heard it. A listener that threw when the scope ended called
  std::terminate. The rollback now notifies, and the destructor logs a
  listener's exception.

Each new test fails without its change.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: read the wallet's status directly when the model is created

Follow-ups from a second local review:

- The model now reads the wallet directly for the status it reports
  while another caller is encrypting, as the table models built just
  before it do. Before, it went through the getters, which already answer
  from the defaults if the encryptwallet RPC has announced an encryption
  but not yet taken the wallet locks.
- encryptWallet() refuses with "Wallet encryption in progress" while this
  model's own worker is running too, so the dialog no longer closes
  silently in that case.
- A single refuseWhileEncrypting() helper now posts the message in place
  of four copies.
- The refresh queued by a notification is dropped once another refresh
  has run. Before, a GUI-started encryption refreshed twice.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: read the wallet's status before building the table models

The previous commit read the status for the encrypting state after the
table models had been built. An encryptwallet RPC that took the wallet
locks between those reads and the table models' own reads stalled
creating the model for the whole encryption. Read the status first:
building the model now waits for an encryption only where the table
models would anyway, the documented limitation.

Also guard the Encrypt Wallet dialog against deletion during the refusal
message's event loop, and fix two comments.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* doc: rename the RPC-encryption GUI release notes after the PR

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 12, 2026
…178)

* qt: keep Encrypt Wallet responsive during existing-wallet encryption

AskPassphraseDialog called WalletModel::setWalletEncrypted from the GUI
thread, and CWallet::EncryptWallet holds the wallet locks while it
encrypts the keys, generates the new descriptors and keypools and
rewrites the database. A populated wallet froze qbit-qt for the whole
operation, so a successful encryption looked like a hung application.

Run the encryption on a worker thread, following the fee-bump worker in
WalletModel: the worker owns a cloned wallet interface, releases the
passphrase and the clone on its own thread, and posts the outcome to the
model through a QPointer and a generation guard. The passphrase dialog
stays open as the non-cancellable progress indicator (busy bar, disabled
buttons, reject/close ignored) until encryptWalletFinished() delivers the
result, then shows the existing success or failure message.

The wallet notifies status and keypool changes from inside the
encryption while it still holds its locks; a listener reading the wallet
on the GUI thread would block on them. Hold those notifications back
while the worker runs and deliver them once it has returned, and skip
the tip-driven PQC status refresh in BitcoinGUI for the same reason.
requestUnlock() and bumpFee() are refused while an encryption is active,
and a second encryptWallet() call starts nothing. ~WalletModel joins the
worker, so wallet unload and application shutdown complete the
encryption before touching the model.

Wallet-layer behaviour is unchanged: the single database transaction,
the rewrite, the key and PQC counter semantics and the encrypted,
locked end state are exactly what the synchronous call produced.

The synthetic test wallet gains an encryption latch that blocks lock-
dependent calls while it is held, so a GUI-thread call into the wallet
during encryption stalls the test the way it stalls the application.
New WalletTests cover the responsive event loop with deferred
notifications, dialog double-submit and dismissal, refused unlock and
fee bump, the failure path, model destruction while encrypting, and a
real funded descriptor wallet that ends encrypted and locked with its
history and address book intact and its keys usable through an
unlock, spend and relock. Against the synchronous implementation the
suite fails at the responsiveness assertion.

Fixes #172

Co-Authored-By: Claude <[email protected]>

* qt: cover remaining GUI reads and exceptions during wallet encryption

Follow-up to the Encrypt Wallet worker: review found two ways the GUI
thread could still reach the wallet while the worker holds its locks,
and one way an exception from the wallet was misreported.

BitcoinGUI::updateWalletStatus runs for every wallet's status change and
reads the current wallet, so another wallet's PQC validation step or
relock during an encryption blocked the GUI thread in CWallet::IsLocked.
Have WalletModel::getEncryptionStatus() and getPQCKeyValidationInfo()
answer from the values taken before the worker started while it runs,
so one guard covers every caller, and drop the narrower guard in
updateWalletPQCValidationStatus. The HD status query in
updateWalletStatus reads the descriptor managers the worker replaces;
skip it until the model refreshes the status on completion. A payment
URI received during the encryption fills in the Send page from the
address book under the same lock; deliver it once the encryption has
finished.

CWallet::EncryptWallet can throw after its database transaction has
committed, from the descriptor setup or the database rewrite. The
worker reported that as success=false and the dialog told the user the
wallet was not encrypted, while the master key was already on disk and
the keys were half encrypted in memory. Carry the exception to the GUI
thread and rethrow it there, so it escapes into the application's
runaway-exception handler and ends the process the way the synchronous
call did; the wallet reloads from what was committed. A clean false
return still reports the failure as before.

When the model is destroyed mid-encryption, the dialog now closes
without done(), because its finished() listeners refresh the wallet
status from the dying model. The null-model check after the
confirmation guarded against an unload that is deferred while a modal
dialog is open; it is an assertion again.

Tests: the synthetic wallet reports itself encrypted from the start of
the operation, as the real wallet does once the master key is stored,
and can throw after its latch is released. New WalletTests cover a
second wallet's status change during encryption and the exception path,
the destroyed-model test checks that finished() is not emitted, and the
real-wallet test reopens the wallet from its records and checks it is
encrypted, locked, still has its history and address book, and unlocks
with the passphrase. Without the model and GUI changes the suite fails
the new assertions without hanging.

Fixes #172

Co-Authored-By: Claude <[email protected]>

* qt: defer transaction-table updates during wallet encryption

TransactionTableModel::updateTransaction() arrives through the event
loop and, for a new transaction, reads it from the wallet under
cs_wallet. With the encryption running on a worker thread the loop is
responsive, so a notification queued as the encryption started was
dispatched while the worker held the lock and blocked the GUI thread
until the encryption finished.

Hold such updates back in the table model while
WalletModel::isEncryptingWallet() and replay them in arrival order from
finishEncryptWallet() after the worker has released the wallet, before
encryptWalletFinished() shows the result. setProcessingQueuedTransactions()
is held back the same way so the balloon limit keeps bracketing the
updates it was queued around.

The synthetic test wallet now waits on its encryption latch in the
transaction reads that take cs_wallet in the real wallet, records the
transaction-changed listeners, and can hold one transaction. The new
WalletTests case raises a CT_NEW notification while the encryption is
held open and checks that the GUI thread keeps servicing events and
that the row appears once the encryption finishes; against the previous
implementation it fails at the watchdog assertion.

Fixes #172

Co-Authored-By: Claude <[email protected]>

* qt: take the wallet lock inside the address-book counting helper

Clang's -Wthread-safety-precise cannot match the lambda's
EXCLUSIVE_LOCKS_REQUIRED(w.cs_wallet) to the caller's
WITH_LOCK(wallet->cs_wallet, ...), so the thread-safety CI builds failed
with -Werror in TestEncryptWalletRealWallet. Lock inside the helper
instead; the test checks the same thing.

Refs #172

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
kiwidream added a commit that referenced this pull request Nov 12, 2026
* wallet: close races around CWallet::EncryptWallet

EncryptWallet decided whether the wallet could be encrypted before it
took the wallet locks, and the key derivation that follows is tuned to
take a noticeable amount of time. A second EncryptWallet caller in that
window, such as the encryptwallet RPC overlapping the GUI worker added
by #178, passed the same check, encrypted the already encrypted keys
and hit the assert in the encryption loop.

Move the already-encrypted and PQC-validation checks under the wallet
locks, after the key derivation. The derivation still runs unlocked so
it does not stall other wallet users, while the check and the
encryption now happen under one lock acquisition, so the losing caller
returns false without touching the wallet. The encryptwallet RPC takes
the same locks before its own already-encrypted check, so an
overlapping RPC call reports the wallet as already encrypted once the
other encryption has finished, instead of a generic failure.

The new master key was inserted into mapMasterKeys before the database
transaction began, so a failed TxnBegin left the wallet reporting
IsCrypted() with nothing written. Insert it only once the transaction
is open and the master key record has been written; a failed write
aborts the transaction. Post-commit failures are unchanged.

IsHDEnabled and GetActiveScriptPubKeyMans read the active manager maps
without cs_wallet, which EncryptWallet replaces under the lock.
GetActiveScriptPubKeyMans, IsActiveScriptPubKeyMan and
ConnectScriptPubKeyManNotifiers now require cs_wallet; IsHDEnabled and
the two callers that did not hold it take the lock.

A test hook parks one EncryptWallet caller between key derivation and
the locks while another completes. Further unit tests cover the failed
TxnBegin and the failed master key write, and wallet_encryption.py
runs two overlapping encryptwallet calls.

Fixes #179

Co-Authored-By: Claude <[email protected]>

* wallet: tighten EncryptWallet race follow-ups

When the encryptwallet RPC encrypts the wallet while the GUI's request is
under way, the GUI's request fails, but the wallet is encrypted with the
RPC's passphrase. The Encrypt Wallet dialog still reported that the
wallet was not encrypted. After a failed encryption the dialog now reads
the encryption status, which the model refreshes once the worker has
returned, and says the wallet was already encrypted by another request
and the entered passphrase was not used. A genuinely unencrypted wallet
keeps the existing message. The synthetic Qt wallet now refuses an
already encrypted wallet as CWallet::EncryptWallet does, and a Qt test
covers the new message.

ConcurrentEncryptWalletLoserFailsCleanly hung instead of failing when
the winning encryption's BOOST_REQUIRE failed: the loser's std::async
future was destroyed, and waited for the parked loser, before anything
released it. A scope guard declared after the future now releases the
loser on unwind.

The EncryptWallet comment said the key derivation does not stall other
wallet users, but the encryptwallet RPC holds the wallet locks for the
whole call; only callers that do not hold them, such as the GUI worker,
avoid the stall. Say so.

Fixes #179

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
kiwidream added a commit that referenced this pull request Nov 12, 2026
…on (#182)

* qt: answer address labels from the table model during wallet encryption

A repaint of the transaction list or the overview page resolves address
labels through AddressTableModel::labelForAddress, which asks the wallet
under cs_wallet. While the encryption worker from #178 holds the wallet
locks, an expose or repaint event stalled the GUI thread until the
encryption finished. No user input is needed: an uncomposited desktop
delivers one behind the application-modal passphrase dialog.

Every wallet read reachable from a paint path during an encryption goes
through that lookup: the ToAddress column's display, edit, tooltip and
foreground roles and the LabelRole and TxPlainTextRole answers in
TransactionTableModel, TxViewDelegate on the overview page and the
label search in TransactionFilterProxy. The other wallet reads in
data(), LongDescriptionRole and TxHexRole, need a user action the modal
dialog blocks; transaction status and balance polling already give up
with TRY_LOCK; the address book and recent-requests views answer from
their own rows, and the coin control view is rebuilt only by the user.

The address book cannot change while the worker holds the wallet, so
AddressTableModel::getAddressData answers from the rows it already holds
while WalletModel::isEncryptingWallet(), found by the encoded address
the rows are sorted on. One guard covers every caller of labelForAddress
and purposeForAddress, and outside an encryption the wallet is asked as
before.

The synthetic test wallet gains an address book and a status for the
transaction it holds, behind the encryption latch like the locks they
stand in for. The new WalletTests case repaints an OverviewPage and
requests every label-bearing role while the encryption is held open,
checks that the GUI thread keeps servicing events and that the labels
match before, during and after the encryption. Against the previous
implementation it fails at the watchdog assertion.

Fixes #180

Co-Authored-By: Claude <[email protected]>

* qt: cover P2MR, sending and refund rows in the encryption label test

The #180 test built its address book from one legacy receiving row, but
every release chain sets fRestrictedOutputMode, so the rows a production
wallet holds are P2MR bech32m addresses, and sending and hidden refund
rows go through the same lookup. A single row also left the search the
model answers from during an encryption with nothing to order.

The synthetic wallet now also pays a labelled P2MR receiving address and
files a P2MR sending and refund address, so the address book mixes both
encodings. The test checks the transaction list roles for the P2MR
payment and the label and purpose of every row before, during and after
the held encryption, which also covers mapping a row's type back to its
purpose. Against a32081e's address table model it still fails at the
watchdog assertion.

Fixes #180

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
kiwidream added a commit that referenced this pull request Nov 12, 2026
* qt: wait for open dialogs before shutdown and wallet unload

BitcoinApplication::requestShutdown() deletes the wallet views. Two
quit requests reach it with no check for open dialogs: the platform's
Quit event (on macOS: Dock > Quit, logout or a Quit Apple event), and
File > Exit pressed through accessibility behind a dialog. Inside the
nested event loop of a dialog, the code after exec() then ran on freed
objects: SendCoinsDialog after the send confirmation, the "PSBT
copied" box or the PQC usage warning shown after a send, and the
passphrase prompt that WalletView keeps on its stack (#349).

Add GUIUtil::IsUserInteractionPending(). It returns true while a
nested event loop is on the stack or a modal dialog other than a
progress dialog is visible. The loop level also covers QMenu::exec(),
and a dialog that done() has already hidden but whose exec() has not
returned. Progress dialogs only report background work, which shutdown
cancels or waits for as before.

requestShutdown() now waits while that holds, retrying every
SHUTDOWN_POLLING_DELAY, and it shuts down only once. Before, a second
request, such as a second platform Quit, requested the node shutdown
again.

Wallet unload checked only the active modal widget. A progress dialog
on top of a dialog in exec(), such as a rescan's progress over the send
confirmation, let it delete the wallet view under that dialog. Unload
now uses the same rule and rechecks it on a timer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt, test: quit while a dialog is open

A process shuts its BitcoinApplication down only once, and AppTests
already uses that shutdown. QuitModalTests therefore runs each
scenario in a child process of test_qbit-qt that is selected through
QBIT_QT_TEST_QUIT_SCENARIO. Each child starts the application with a
synthetic wallet and requests a quit while a dialog is open. It checks
that the shutdown waits, then answers the dialog and checks that the
shutdown runs exactly once. A second platform Quit and File > Exit
during the node shutdown are then ignored.

- The platform Quit event and File > Exit inside the send confirmation,
  the "PSBT copied" box, the PQC usage warning after a send, and the
  passphrase prompt of a locked wallet. Nothing is sent or signed that
  the user did not confirm.
- A quit handled in the same event pass that closed the confirmation.
- A quit during wallet encryption and during PSBT signing after the
  counters were reserved (#174 C4). Both wait for the operation and for
  the user to close its dialog.
- A wallet unload while a rescan progress dialog covers the send
  confirmation.
- A quit with the console's command completer and a QMenu::popup() menu
  open, which must not wait.

Without the fix, the send-flow and unload scenarios abort under
AddressSanitizer with a heap-use-after-free or an invalid free, and the
others fail their checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: shut down once the main window exists and ignore a late init result

A platform Quit can arrive before GuiMain has created the main window,
for example during the Intro dialog. requestShutdown() deferred it while
the dialog was open. A retry in the pass that closed the dialog, at loop
level one, could still run it with no window and fail the assertion in
ShutdownWindow::showShutdownWindow(), as the quit did before at once.
It now also waits until the window exists.

A quit during initialization tears the GUI down and requests the node
shutdown, but initialization can still report success afterwards.
initializeResult() then created the client model and the wallet
controller and showed the window again. Before, the shutdown poll tore
those down a second time. Since requestShutdown() runs only once, they
would have stayed alive while the node unloaded its wallets.
initializeResult() now returns once the shutdown has started.

The run-once check in QuitModalTests now also asserts that it ran
before the node shutdown ended, and delivers a successful
initialization result at that point. A new scenario quits before the
main window exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* doc: name the quit-modal release note after #354

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: close an unloaded wallet's rescan progress and show what a quit waits for

WalletView::showProgress() creates its rescan progress dialog without a
parent, and ~WalletView left it open. When a wallet was unloaded under
that dialog, the dialog stayed visible and application-modal. The
shutdown poll, which runs only when no modal widget is active, then
ignored RPC stop and SIGTERM until the user cancelled the orphaned
dialog. ~WalletView now hides the dialog and deletes it later. The
destructor can run inside the dialog's own setValue(), which processes
events.

When requestShutdown() first defers a quit, it now shows the main
window if it is hidden or minimized, then raises and activates the
dialog that the quit waits for. A quit that seems to be ignored invites
a force quit, which skips the node's flush. It raises the dialog
directly: on Wayland, GUIUtil::bringToFront() re-creates the window,
and hiding a dialog ends its exec().

The release note now says that macOS cancels a logout started while
such a dialog is open, as it did before, and that qbit-qt quits once
the dialog is closed. It also notes that RPC stop and SIGTERM now wait
for an open context menu too.

QuitModalTests:
- The send-confirmation scenario checks that the deferred quit
  restores a minimized main window.
- A new unload-rescan-stop scenario unloads a wallet under its rescan
  progress dialog and stops the node.
- The latch that keeps a build without the fix from hanging starts its
  clock at the quit instead of at startup, with a 30 s limit, so slow
  hosts cannot fail the test spuriously.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt, test: skip the quit-modal scenarios when Qt lacks QProcess

The depends Qt for Linux is built with -no-feature-process, so <QProcess>
declares nothing there and the CentOS depends and i686 no-IPC GUI jobs
failed to compile quitmodaltests.cpp. Guard the child-process runner
with QT_CONFIG(process) and QSKIP the case otherwise, so it shows as
skipped instead of disappearing. Builds against a Qt with QProcess
(macOS, Windows, and Linux system-Qt jobs) still run every scenario.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: defer quit and unload only for nested and native dialog loops

After rebasing onto 1.x.x, #344's AppTests timed out: it quits while
two PSBT dialogs, shown with ShowModalDialogAsynchronously(), are
signing, and expects the shutdown to hide them and keep their results.
IsUserInteractionPending() counted every visible modal widget, so the
quit waited for those dialogs indefinitely.

Defer shutdown and wallet unload only while a caller that would return
into the deleted wallet views is on the stack:
- a nested QEventLoop, as QDialog::exec() and QMenu::exec() run
  (loopLevel() > 1; every caller runs from the GUI thread's event loop);
- a native message box or file dialog, which runs the platform's modal
  loop instead (on macOS, [NSApp runModal]). In Qt 6.8, which depends
  pins (#347), QMessageBoxPrivate::setVisible() and
  QFileDialogPrivate::setVisible() call setNativeDialogVisible(), set
  WA_DontShowOnScreen and then call QDialogPrivate::setVisible(), so a
  visible modal widget with WA_DontShowOnScreen stands in for the native
  dialog. A Qt upgrade must re-check this. qbit sets the attribute
  nowhere else.

Qt dialogs shown without a loop of their own are on screen, have no
caller to return into, and no longer hold up a quit or an unload. The
wallet unload deferral uses the same rule, so unloadwallet is not
blocked by an open PSBT dialog.

Audit of asynchronously shown or non-exec dialogs that hold wallet
references, which 1.x.x's unload deferral had covered:
- CoinControlDialog had no parent but refers to its SendCoinsDialog's
  CCoinControl and WalletModel. An unload would delete both under it.
  Parent it to the SendCoinsDialog, so it is deleted with it.
- Safe: EditAddressDialog (address book page, transaction view),
  AskPassphraseDialog (encrypt, change passphrase),
  SignVerifyMessageDialog and ReceiveRequestDialog are children of the
  wallet view or its pages; PSBTOperationsDialog handles unload (#344);
  RPCConsole handles removeWallet; TransactionDescDialog copies its text
  and its view closes it; Options and About hold no wallet references;
  the wallet activity dialogs hold no loaded wallet; the fee-bump
  confirmation runs exec(); progress dialogs are unchanged.

Tests: an in-process check of the rule (runs without QProcess), and
quit-modal scenarios where a native-marked dialog defers quit and
unload, an open PSBT dialog does not hold an unload, and an unload
deletes an open Coin Control dialog. The encryption and PSBT signing
scenarios now expect the shutdown to start at once, with teardown
waiting for the work that cannot be cancelled. Each new or changed test
fails with the previous rule, without the Coin Control parent, or
without the native-dialog check. Native dialogs cannot be shown on
Linux CI, so the native path is tested through the attribute Qt sets.

Also update the comments that described the old rule (#178's in
AskPassphraseDialog::accept, #348's above
TestSendDestructionDuringConfirmation).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: document the shutdown gates for quit and stop

The release note described the earlier rule. Correct it for the final
one:
- A platform or menu quit during wallet encryption or PSBT signing starts
  the shutdown at once; the shutdown waits for the work, and the "Wallet
  encrypted" box is not shown.
- The rules about dialogs apply to platform and menu quits only.
- RPC stop and SIGTERM keep upstream's rule: the GUI shuts down only while
  no modal dialog is open, including progress dialogs and dialogs such as
  the PSBT dialog.
- A second quit request is ignored, a quit during the first-run data
  directory dialog is carried out after startup, and most context menus
  hold a quit or stop until they close.

Add comments at the shutdown poll and at IsUserInteractionPending() that
explain why the two paths differ. No behavior change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 12, 2026
…it (#352)

* qt: keep the GUI responsive during wallet encryption started outside it

The Encrypt Wallet dialog runs the encryption on a worker thread and puts
WalletModel into a mode in which status, PQC validation and label reads
answer from cached values, and status, keypool and transaction-table
updates are held back (#178, #182). That mode engaged only when the GUI
started the encryption. The encryptwallet RPC holds the wallet locks for
the whole call while it generates the new keys, so it stalled the GUI
thread on those locks. On 2026-11-04, `qbit-cli encryptwallet` with
-keypool=3000 froze qbit-qt for about 200 seconds.

CWallet::EncryptWallet now counts itself in progress from its first line
until it returns or throws, whoever called it, and it raises
NotifyEncryptionInProgressChanged when it starts and when it ends. The
counter is an atomic that reads no wallet state, so the GUI can query it
without waiting for the locks. interfaces::Wallet exposes it as
isEncryptionInProgress() and handleEncryptionInProgressChanged(). The
announcement does not change the encryption itself: the #183 checks and
the #277 lock order are untouched, and an overlapping encryptwallet call
still returns -15 (RPC_WALLET_WRONG_ENC_STATE).

WalletModel::isEncryptingWallet() now also reports an encryption that the
wallet announces, so every guard from #178 and #182 covers it: the
encryption status, the PQC validation status, label lookups, status and
keypool notifications, transaction-table updates, the HD status in the
status bar, payment URIs, unlock requests and fee bumps. The model enters
this state the first time it sees the encryption and leaves it only when
it handles the wallet's notification that the encryption ended. Updates
held back in the meantime are therefore delivered before newer ones. The
notification is queued, and the model reads the in-progress state instead
of relying on the order in which notifications arrive, so a start that is
announced after the end cannot leave the model stuck.

When the encryption ends, the model refreshes the status from the wallet
whatever the outcome, including a failure, or an exception that skipped
the wallet's status notification. It then delivers what it held back and
emits the new walletEncryptionEnded() signal, which payment URIs now wait
for. The dialog's own result waits until every encryption in progress has
ended. If another encryption holds the wallet when the dialog's request is
refused, the dialog reports "already encrypted by another request" once
that encryption has finished, instead of reading the status from before
it.

The listener only posts a queued call and never waits for the GUI thread.
The notification can therefore be raised while the encryptwallet RPC holds
cs_wallet without deadlocking against a GUI-thread call that waits for
that lock. GUI actions that the user starts and that need the wallet, such
as creating a receiving address, still wait for an encryption started
outside the GUI, as in v1.0.0. The release notes list them.

The synthetic test wallet now announces its encryption. New WalletTests
start an encryption from another thread, as the RPC does, and hold it
open:

- The GUI thread keeps servicing events while the reads answer from the
  model, and the held-back updates are delivered once the encryption ends.
- A failure, an exception and a late start announcement each end the mode
  and refresh the status.
- A dialog request refused during another encryption reports the right
  result.
- Deleting the model, as unloading the wallet does, does not wait for the
  encryption.

A further test encrypts a real descriptor wallet with the wallet locks
held, as the RPC does, and parks it inside its database transaction. The
GUI stays responsive, a GUI-thread call that waits for cs_wallet completes
once the encryption has finished, and the model then reports the wallet as
encrypted and locked. Without the WalletModel changes, each new test fails
at its watchdog assertion.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* wallet: announce RPC encryption before taking the wallet locks

The encryptwallet RPC takes m_relock_mutex and cs_wallet before its
checks, and GetPQCKeyValidationInfo then waits for every descriptor
manager's cs_desc_man. A background P2MR refill or create-time top-up step
holds cs_desc_man without cs_wallet while it derives and writes keys, so
the RPC can sit with cs_wallet held before EncryptWallet raises the
in-progress counter. A GUI read in that window, such as a label lookup
during a repaint, waited for cs_wallet and so for the whole encryption:
the stall the previous commit fixes.

The counter and its notifications move into an RAII
CWallet::EncryptionInProgressScope. EncryptWallet holds one as before,
and the encryptwallet RPC now takes another before LOCK2. The counter
nests. The RPC's scope ends after the locks are released, so a call that
fails, or that finds the wallet encrypted and returns -15, also ends with
the GUI reading the wallet again. The scope does not touch the RPC's
checks or the lock order from #183 and #277.

A new WalletTests case runs the encryptwallet RPC against a real
descriptor wallet while a thread holds a descriptor manager's lock, the
way a keypool step does. The GUI keeps servicing events while the RPC
holds cs_wallet and waits for that lock, and the model answers from what
it last read. The encryption then completes, and a second call returns
-15 and still ends with walletEncryptionEnded(). Without the RPC's scope,
the test fails at its watchdog assertion.

The same test also covers an encryption that throws from
m_before_encrypt_wallet_locks: the announcement ends, and the model
reads the wallet again.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: refuse Encrypt Wallet while another encryption runs

While another caller, such as the encryptwallet RPC, was encrypting the
wallet, the GUI still showed it as unencrypted and accepted a request from
the Encrypt Wallet dialog. The worker then derived a key and waited for the
other encryption's locks. The dialog showed its progress bar for the rest
of that encryption, and only then reported that the wallet had been
encrypted by another request. Meanwhile ~WalletModel would have waited for
the worker.

WalletModel::encryptWallet() now refuses while isEncryptingWallet(), with
the "Wallet encryption in progress" message that unlock requests and fee
bumps get, and starts nothing. The dialog then closes without claiming a
result.

The dialog's own result still waits for every encryption in progress. The
encryptwallet RPC announces its encryption before it waits for the locks,
which can happen while the dialog's encryption holds them. The test that
covered this now exercises that order: the synthetic wallet can announce
an encryption without holding its latch, as the RPC does while it waits.
A new test covers the refusal and fails without it.

The release notes add opening a wallet in the GUI while it is being
encrypted to the known limitations: the model reads the wallet when it is
created.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: tighten the wallet-announced encryption mode

Follow-ups from a local review of this branch:

- The Encrypt Wallet dialog decided whether another encryption had
  refused its request by checking isEncryptingWallet() after the call.
  The model's "Wallet encryption in progress" message runs a nested event
  loop, which can see that other encryption end. The dialog then reported
  a result for an attempt the model never made. It now checks before
  asking, and WalletView refuses to open the dialog while another
  encryption runs, before the user has chosen a passphrase.
- WalletModel now reads the encryption and PQC validation status once it
  has subscribed to the wallet. A model that had not been asked for them
  before another caller started encrypting reported the defaults: an
  encrypted wallet showed as unencrypted while a refused encryptwallet
  call waited for the locks.
- encryptWallet() no longer resets the status the model last reported.
  Doing so could swallow an encryptionStatusChanged() whose notification
  was still queued. The getters now record the values that the GUI is
  answered from.
- Each encryption raises several notifications, and they can all be
  queued while the GUI thread is busy. The model now coalesces the
  refresh at the end of an encryption into one.
- If a listener threw from EncryptionInProgressScope's constructor, the
  announcement was rolled back without telling the listeners that had
  already heard it. A listener that threw when the scope ended called
  std::terminate. The rollback now notifies, and the destructor logs a
  listener's exception.

Each new test fails without its change.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: read the wallet's status directly when the model is created

Follow-ups from a second local review:

- The model now reads the wallet directly for the status it reports
  while another caller is encrypting, as the table models built just
  before it do. Before, it went through the getters, which already answer
  from the defaults if the encryptwallet RPC has announced an encryption
  but not yet taken the wallet locks.
- encryptWallet() refuses with "Wallet encryption in progress" while this
  model's own worker is running too, so the dialog no longer closes
  silently in that case.
- A single refuseWhileEncrypting() helper now posts the message in place
  of four copies.
- The refresh queued by a notification is dropped once another refresh
  has run. Before, a GUI-started encryption refreshed twice.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* qt: read the wallet's status before building the table models

The previous commit read the status for the encrypting state after the
table models had been built. An encryptwallet RPC that took the wallet
locks between those reads and the table models' own reads stalled
creating the model for the whole encryption. Read the status first:
building the model now waits for an encryption only where the table
models would anyway, the documented limitation.

Also guard the Encrypt Wallet dialog against deletion during the refusal
message's event loop, and fix two comments.

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* doc: rename the RPC-encryption GUI release notes after the PR

Refs #174

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 12, 2026
## Summary

This lands the v1.0.1 release branch on `main` as one commit, the same way `main` received v1.0.0 in #135. The `v1.0.1` tag will then be created on the resulting `main` commit.

- **Source:** release branch `1.x.x` at `a7a70660ad6ecadbf77b89bc2fe85ba068a86a71`, this PR's head before the signed squash. `main` (`70fea84f5b`) is an ancestor of that commit, so the squash has exactly its tree: `35a01d570ceef5984ae84e15d4dc74adecb587be`.
- **Signing:** the release coordinator squashes the head into one commit and signs it with `squash-sign`. The tree does not change.
- **Rebuilt head:** this branch replays the 75 commits of `1.x.x` since `main` (`70fea84f5b..a7a7066`) with their trees, messages and authors unchanged, so their SHAs differ from `1.x.x`'s. The one change: #268 (`e374ba24cf`) is split into its pure libbitcoinpqc v0.3.2 import, which carries the subtree's directory and split (`1965d0da1e`) trailers, and the rest of #268. That way the squash keeps the subtree trailer that `test/lint/libbitcoinpqc-subtree-check.sh` needs on `main`. Without it, the check would find v0.1.1's split `ac72d1ffa0` and fail. The final tree is still `35a01d570ceef5984ae84e15d4dc74adecb587be`.

## Validation of this tree (on `a7a70660ad`)

- Full Validation [43271045040](https://github.com/Qbit-Org/qbit/actions/runs/43271045040): passed.
- Required Merge Gate [43271044819](https://github.com/Qbit-Org/qbit/actions/runs/43271044819): passed.
- Core Checks [43271044808](https://github.com/Qbit-Org/qbit/actions/runs/43271044808), including the `mainnet publication posture` job: passed.
- Nightly CI [43273463067](https://github.com/Qbit-Org/qbit/actions/runs/43273463067): dispatched on this commit. Its scanner results are triaged, and one job is being re-run after a runner infrastructure failure.
- The release notes are `doc/release-notes-1.0.1.md`, from #181. The freeze and the changes since v1.0.0 are tracked in #174.

## Review

Please review the release as a whole against `v1.0.0` (`git diff v1.0.0 a7a7066`), or through the individual `1.x.x` PRs listed in #174 and the release notes. This PR adds nothing beyond `1.x.x` at `a7a70660ad`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
5aa60b3 fix: resolve finalized mainnet CI failures (#137)
b83f87d wallet: avoid deferred keypool unlock deadlock (#143)
0716a7c qt: move PSBT signing off GUI thread (#145)
141a9de Build versioned RPC docs pages (#148)
73c064a test: stabilize REST chaininfo comparison (#149)
508c6ea wallet: default -fallbackfee to the minimum relay fee (#151)
6f703b6 wallet: publish descriptor top-ups after commit (#144)
f9172e8 wallet: show fee-only change-only self-transfers (#150)
6de89ab qt: show consumed PQC usage when a generated proof fails verification (#129) (#161)
9084d83 fuzz: seed qbit targets and verify replay and mutation (#164)
df533c5 qt: preserve and display consumed PQC usage in transaction signing flows (#167)
fc835f4 ci: run classifier tests in Required Merge Gate (#160)
2053d83 release: fail closed when the release asset list cannot be read (#170)
7f11260 ci: harden the Required Merge Gate check-run poller (#171)
5b80d5f ci: validate maintained source in scheduled heavy workflows (#165)
4873900 wallet: batch P2MR counters across mixed descriptors (#163)
19043e0 script: cache successful P2MR PQC signature checks (#162)
b262cd0 ci: forward IBD workflow timeout inputs to the harness flags (#159)
4b89e4a doc: correct the v1.0.0 release trust record (#175)
0d2de1e fuzz: repair stale pqc_sign_refused coverage anchor (#176)
0954b74 qt: keep fee-bump PQC usage visible without a notification backend (#177)
3ccf788 qt: keep Encrypt Wallet responsive during existing-wallet encryption (#178)
6d6cc7d wallet: close races around CWallet::EncryptWallet (#183)
54f6737 qt: answer address labels from the table model during wallet encryption (#182)
1339e6b doc: fix pipe rendering and tighten P2MR v1 consensus profile (#252)
422ba0e doc: document bounded30 usage-dependent security margin and raw-key counter limits (#264)
981605a script: cache verified P2MR data-signature checks (v1.0.1) (#265)
a5292af policy: bound P2MR runtime stack bytes (#263)
d3b02f4 net: bound the size of headers messages we send (#266)
0c60e64 Squashed 'src/libbitcoinpqc/' changes from ac72d1ffa0..1965d0da1e
2f6992b subtree: import libbitcoinpqc v0.3.2 signer stack scrub (#268)
cbb1961 crypto: clear stack released by PQC secret-key operations (#270)
260ac73 wallet: take descriptor locks before EncryptWallet's transaction (#277)
243065c mining: reset cached block checks in IPC submitSolution (backport bitcoin/bitcoin#33745) (#289)
bc9f1bd wallet: keep the SQLite lock when probing loaded wallet files (#297)
95b8b9f wallet: fail a send whose inputs a concurrent call spent (#298)
ad3d708 depends: Update Qt to 6.8.4 and fix macOS accessibility use-after-free (#347)
660034c fuzz: re-anchor PQC coverage checks after #270 and run them in CI (#342)
b178391 wallet: deferred P2MR keypool refill at startup and unlock; Lock() waits for key copies (#299)
6700285 test: fix race in p2p_auxpow_headers_size (#358)
f6c2013 qt: fix send confirmation re-entrancy and dialog deletion during confirmation (#348)
1fe12ea wallet: fallback-fee follow-ups for #151 (discard rate, GUI warning, default test, help texts) (#346)
d21acc4 ci: bind the Required Merge Gate to its own event's runs, fail drafts, keep both sides of renames (#345)
a4e1f26 qt: keep PSBT signing results across shutdown, close and unload (#344)
e783923 test: keep wallet_p2mr_deferred_keypool_tests within time limits under sanitizers (#361)
1538eed ci: run runner selection on GitHub-hosted Ubuntu (#362)
1b8d10f qt: ignore PSBT Sign while a signing attempt is in progress (#353)
01a9ab3 contrib: import libbitcoinpqc releases as one verified main-line commit (#360)
5b42181 guix: ship macOS debug symbols as dSYM bundles (#343)
6f080f0 wallet: remove deleted plaintext keys from the wallet file after encryption (#300)
98dbe5b wallet: re-encrypt plaintext PQC keys in encrypted wallets on unlock (#301)
dff82fb ci: allowlist fuzz-seed format tags in the gitleaks scan (#367)
c7c9fbd ci: retry the cargo-audit database fetch and fix the clang analyzer scan (#368)
8ee5231 contrib: add the rulesets for qbit-guix.sigs main (#371)
f8ababf contrib: add public tools to stage, sign and combine release checksums (#374)
c4d88af contrib: keep the release key policy in one place and tighten key-policy continuity checks (#375)
78405ad wallet: keep the lock state when changing the passphrase (#379)
ea99d08 ci: keep the 32-bit ARM nightly unit-test shards within their time limit (#377)
cb1f507 ci: run the mainnet publication posture check on every mainnet line (#385)
6582427 qt: wait for open dialogs before shutdown and wallet unload (#354)
7953475 qt: keep the GUI responsive during wallet encryption started outside it (#352)
0d87213 doc: replace the release docs with a runbook, a publisher reference and a release issue form (#376)
3de5e93 net: only use service bits learned from a direct connection when deciding which addresses to avoid (#380)
565eb46 photon: bound inbound relay state per peer and check blocks before submission (#381)
7b7066f ci: parse gpg status output on newline only and reject other line separators (#387)
b1b0860 net: budget per-peer time spent validating rejected transactions (#386)
3ae934c photon: announce blocks under the low-order bits of their hash (#410)
faaaaa8 wallet: refill P2MR keypools before walletpassphrase returns (#411)
9e74401 wallet: fail descriptor key encryption when the plaintext record is not erased (#418)
e8a796d ipc: return false from submitSolution for a missing or undecodable coinbase (#419)
396940d net: request transactions held back by the validation budget later, and limit each connection's share of the pool (#422)
6ca0132 net, validation: attribute received blocks to their sender and check recovered blocks (#414)
c65bea2 qt: add a play-money poker lobby based on Satoshi's 2009 design (#378)
b3b5096 script: limit standard hashing of large P2MR stack elements (#415)
ca5d4b5 release: prepare v1.0.1 (#181)
b1c6d4e net: pass held-back transaction announcements on at most once per retry delay (#425)

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Alexander Miller <[email protected]>
Co-authored-by: Sjors Provoost <[email protected]>
Co-authored-by: Fabian Jahr <[email protected]>
Co-authored-by: Dan Hepworth <[email protected]>
git-subtree-dir: src/libbitcoinpqc
git-subtree-split: 1965d0da1eb4d9e196613b8f3a5d0d866a221c53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant