qml: Move wallet overview, activity, address and receive work off the GUI thread

bitcoin-core/gui-qml: PR #1146

7 minor findings · 6 suggestions

Earlier concerns neither republished nor resolved: 1 minor finding · 2 suggestions. See the Run archive for their assessments.

Findings

Link

[minor] · Signing reads encryption state without synchronization

On an initially unencrypted wallet, background signing can race with GUI encryption because its isCrypted() calls read Core's master-key map without cs_wallet.

Location: qml/models/signverifymessagemodel.cpp:76 (head).

Details and suggested fix

Start signing, return to wallet settings, and set a password while the signing task remains queued or running. Leaving the signing page calls clear(), but that only changes result generations and does not cancel the task. The worker calls isCrypted() before acquiring the unlock session and again afterward. In pinned Core, this reads !mapMasterKeys.empty() without locking, while EncryptWallet() inserts into that map under cs_wallet. GUI encryption neither takes the session nor excludes pending signing, so these accesses form a C++ data race. Read the signing task's security state under cs_wallet, including the initial session-selection check, as ReadSecurityState() already does for snapshots.


Link

[minor] · Send can use a selected coin while its lock is pending

Locking a manually selected Send input now leaves it selected until worker completion, allowing Review to prepare and sign a transaction containing that coin in the meantime.

Location: qml/components/CoinsList.qml:62 (head).

Details and suggested fix

With a settled Send draft, open the wallet's Coins view, lock one of its manually selected inputs, and return to Review before the asynchronous command completes. setCoinsLocked() leaves m_coin_control unchanged until its completion handler, while prepareTransactionInternal() immediately copies that selection without checking coinLockPending. Explicitly selected inputs can still be used by Core even after their backend lock takes effect, so this bypasses the GUI's “Use locked coin?” confirmation. Later unselection does not discard the prepared transaction. Block preparation and disable Review while the lock command is pending. The overlap depends on worker timing; its duration was not measured.


Link

[minor] · A busy unlock session makes the fee bump impossible to retry

The transient busy path moves BumpTransactionModel to Failed, disabling Update and rejecting password resubmission until the overlay is closed and reopened.

Location: qml/models/bumptransactionmodel.cpp:160 (head).

Details and suggested fix

On an encrypted wallet, signing or Receive preparation can hold the shared unlock session when fee-bump confirmation calls tryAcquire(). Failure calls setError(), which sets Failed, despite telling the user to try again shortly. Subsequent confirmation calls return immediately because they require NeedsConfirmation, and the Update button uses the same state requirement. A password popup already open remains open but cannot retry successfully. Report this transient error without leaving NeedsConfirmation, and ensure the overlay displays that recoverable error. Closing and reopening currently recovers by preparing the bump again.


Link

[minor] · lockunspent can leave the cached Send balance stale

An RPC lock change between the balance read and lock-set checkpoint can leave Send using the old available balance until another refresh trigger; this interleaving was not reproduced.

Location: qml/models/walletstatesnapshot.cpp:142 (head).

Details and suggested fix

read() obtains available_balance before reading locked outputs into m_locked_coins, and these Core calls take cs_wallet separately. A lockunspent call between them produces an old balance paired with the new lock checkpoint. Later polls see the same lock set, and Core's lock operations emit no notification, so the balance can remain stale until a block, wallet notification, or payment change triggers another read. This can wrongly block or enable Review, although preparation checks Core again. Capture the lock-set checkpoint before reading the balance so a subsequent lock change remains detectable by the next poll.


Link

[minor] · Delayed signing opens its password prompt over Verify mode

Switching to Verify while signing is pending can bring up “Unlock and sign” over the Verify form, although submission still signs the previously submitted Sign-tab message.

Location: qml/pages/wallet/SignVerifyMessage.qml:84 (head).

Details and suggested fix

The mode picker remains enabled while the signing task waits on the wallet executor because it sits outside the disabled StackLayout. If the user selects Verify before a needs-unlock result arrives, onSigningFinished() opens signPassphrasePopup based only on signingNeedsUnlock and page visibility. Its submit handler still uses signAddressModel.address and signMessageText.text, now hidden behind the Verify form. Open this prompt only when selectedMode is the Sign tab, or restore that tab before presenting it, and cover the delayed completion in a QML test.


Link

[minor] · A pending verification retains the previous result banner

Although edits already retained the previous banner, asynchronous submission now also leaves it beside the newly submitted inputs until verification completes.

Location: qml/pages/wallet/SignVerifyMessage.qml:76 (head).

Details and suggested fix

submitVerify() queues work without clearing verifyResultText or verifyResultSuccess. The banner remains shown whenever that text is nonempty, and only onVerificationFinished() replaces it. Because verification shares the wallet executor with snapshot reads and Receive commands, the previous success or failure can remain throughout a queue delay. The form is disabled during this interval, but the result text still describes the earlier check. Clear the page-local result before submission, or replace it with an explicit pending state.


Link

[minor] · Automatic Receive preparation replaces the pending address-type choice

If a typed address preparation needs unlock and automatic preparation overlaps it, the password retry can use the previous preference instead of the user's chosen type.

Location: qml/pages/wallet/ReceivePage.qml:36 (head).

Details and suggested fix

ensureReceivingAddress() assigns pendingAddressType before checking receiveOperationPending. After the user chooses type X, returning to Receive while that operation is pending calls prepareReceivingAddress() with an empty type when an address already exists. If X's derivation then needs unlock, the deferred branch can discard that automatic request as already satisfied, but the password handler still retries with the overwritten empty type. Since the backend has not persisted X, the retry keeps or derives an address using the previous preference. Keep the submitted user intent separate from automatic preparation and use that intent for the unlock retry. The frequency of typed derivations requiring unlock is not established.


Optional improvements

Link

[suggestion] · Save and EnsureAddress hold cs_wallet across snapshot-only work

Receive preparation holds cs_wallet through balance calculations, coin collection, transaction scanning and settings reads, extending exclusion beyond the reservation checks and writes; stall duration was not measured.

Location: qml/models/walletstatesnapshot.cpp:325 (head).

Details and suggested fix

execute() acquires cs_wallet before the full read(node) for Save and EnsureAddress. It releases the lock only after address derivation and request or label writes, while finish() subsequently performs another full read. Atomic reservation checks are necessary, but unrelated balance, coin-list and settings work need not extend that critical section. Separate snapshot-only work from the state required by the command, keeping the observed-payment and saved-request checks, derivation and writes atomic under cs_wallet. This reduces blocking of validation callbacks, RPCs and synchronous GUI callers without weakening address-reuse protection.


Link

[suggestion] · Wallet snapshots discard an existing Send fee preview

For a valid Send draft, every applied snapshot clears the fee preview and disables Review, including snapshots from label or Receive commands that leave the draft unchanged.

Location: qml/models/walletqmlmodel.cpp:734 (head).

Details and suggested fix

applyWalletState() always calls scheduleFeeEstimates(), which clears the previous estimates, sets feeEstimatePending, and restarts the estimator timer. The displayed fee then becomes “—” and Review is disabled until another queued estimate completes. Retain the last successful preview during a background refresh of an unchanged draft, rather than treating that refresh like a draft edit. Preparation already recomputes the transaction, so this can avoid unnecessary interruption while still refreshing estimates when blocks or wallet state change. The duration and frequency of this UI churn were not measured.


Link

[suggestion] · Lightweight Receive commands perform an unnecessary full pre-read

RememberAddress, Label, Remove and AddressType each perform two full wallet reads despite needing little or none of the first snapshot.

Location: qml/models/walletstatesnapshot.cpp:328 (head).

Details and suggested fix

execute() calls read(node) before dispatching every command, then complete() calls it again through finish(). The first scan gathers balances, addresses, coins and transaction history even though RememberAddress only writes QSettings, Label and Remove need saved requests, and AddressType needs capability and preference data. These scans occupy the serial worker while receiveOperationPending remains set. Skip the initial read for RememberAddress and use targeted prerequisite reads for the other lightweight commands, retaining final reconciliation and the existing pre-read for Save and EnsureAddress. The runtime cost was not measured.


Link

[suggestion] · read() calculates an unused balance for its block checkpoint

tryGetBalances() computes a balance that the snapshot reader discards, and a contended TRY_LOCK leaves the checkpoint empty, causing another full read on a later poll.

Location: qml/models/walletstatesnapshot.cpp:137 (head).

Details and suggested fix

In pinned Core, tryGetBalances() reads the block hash and calls getBalances(), which computes GetBalance. The snapshot uses only the hash and immediately calls getBalance() again. If the initial TRY_LOCK fails, the remaining blocking reads can still succeed, but m_last_processed_block stays empty and the next successful poll repeats the full snapshot read. For a local wallet, obtain GetLastBlockHash() under a blocking cs_wallet lock before scanning, following the hash-only approach already used by poll(). Keep tryGetBalances() as the non-local fallback.


Link

[suggestion] · The QML settings fixture uses a different completion contract

The test fixture returns queued acceptance from password and backup operations, while production returns completed success or failure and the settings QML treats that boolean as final.

Location: test/qml/qml_tests_main.cpp:1706 (head).

Details and suggested fix

Fixture encryption and passphrase changes return startSettingsOperation() before a zero-delay timer applies success; backup similarly defers its effects. Production completes these methods synchronously, and WalletPasswordSettings.handleSaveResult() immediately clears fields, reports success, or leaves the page based on their return value. No QML test uses the added asynchronous controls or completion signal, so this alternate protocol adds no exercised failure coverage. Make the fixture methods synchronous with configurable results, applying security and backup state before returning, and remove the unused asynchronous scaffolding.


Link

[suggestion] · Batch-lock failures discard the marked coins

As in base, a failed batch lock leaves the user marking coins again to retry; the asynchronous flow now clears those marks before the outcome is known.

Location: qml/components/CoinsList.qml:64 (head).

Details and suggested fix

lockMarked() clears markedIds when setCoinsLocked() returns true, which now means only that the command was accepted. A later worker or database failure appears through lockOperationError after the submitted marks are gone. Retain the submitted IDs until completion and clear their marks on success, leaving surviving marked coins available for retry on failure. Keep the existing immediate-rejection handling.


Coverage details

Earlier concerns

Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

The Node/Wallet interface boundary was introduced to centralize GUI/backend communication, support mocking and eventual IPC, and make blocking accesses easier to identify. It was deliberately distinct from higher-level Qt MVC models and did not itself make calls asynchronous.

The affected code calls interfaces::Wallet but also uses local-wallet access for locking and descriptor inspection. The historical boundary explains why an interface call cannot be assumed cheap or nonblocking, and why worker scheduling remains a separate concern. The pinned build links the Core libraries into the QML application; historical IPC motivation is not evidence that this configuration uses remote wallets.

Source 1 · Source 2 · Source 3 · Source 4

Explicit task outcomes arose because merely running a closure in the background leaves application state ambiguous when submissions are rejected, owners disappear or shutdown suppresses callbacks. Issue #1054 sought request identity, terminal outcomes and replayable drain observation; #1109 narrowed that work to outcomes, cancellation and draining while preserving worker-side cleanup.

This explains the dependency commits included here and the distinction between cancelling queued work, discarding a running query's eventual result, and draining accepted work. The head executor contract explicitly leaves running work uninterrupted and waits for worker cleanup, rather than treating a cancellation notification as proof that backend execution has stopped.

Source 1 · Source 2

Asynchronous Receive operations must distinguish durable backend completion from presentation in the current view. The earlier Receive issue explicitly required successful changes to remain associated with their original wallet while preventing delayed saves, deletions or errors from affecting newer drafts, reopened dialogs or another wallet with the same request ID.

This is the rationale for wallet identity and numbered dialog openings in the affected QML, rather than relying only on visibility or a request ID. It also explains why switching away need not undo a successful save, while its completion must not clear a newer draft or close another opening.

Source 1 · Source 2

Unlocking and relocking have historically been treated as wallet-wide lifetime operations, not independent per-call toggles. A 2020 Core change serialized walletpassphrase calls and ignored obsolete relock callbacks. A 2022 change introduced a relock mutex so timeout-driven locking could not erase key material while a rescan still needed it.

These precedents explain why moving message signing and Receive work to a worker creates an unlock-lifetime question beyond ordinary wallet-data locking. They also establish that relocking can have its own lock ordering. They do not establish that Core's RPC mutexes automatically serialize this application's Send, Receive and signing workflows.

Source 1 · Source 2

Receive history historically provided a way to redisplay an invoice without generating a new request using an old address. The 2014 removal of the address-reuse option explicitly cited request history as replacing the resend justification; the removed UI warned that reuse has security and privacy consequences.

This supplies the older rationale behind distinguishing reopening an existing request from allocating an address to a new one. The head backend checks both previously observed payments and saved requests before offering a stored receiving address, so an unpaid saved request also reserves its address.

Source 1 · Source 2

Current payment status and historical address exposure serve different purposes. Issue #1042 documented a payment replaced by a transaction paying elsewhere: the currently received amount became zero, but the permanent observed-payment flag still drove a success badge. Its stated distinction was to update the displayed status while retaining sharing and reuse restrictions.

This explains why the payment badge changes independently of the observed-payment flag. The base already excluded inactive unconfirmed payments from received totals while retaining address history; the head snapshot continues that separation and polls outstanding payments because mempool eviction need not notify the receiving wallet. This is wallet accounting and presentation context, not a protocol change.

Source 1

QR export has two distinct success conditions: capturing or writing an image and successfully encoding the payment request. Earlier Receive discussion documented an oversized URI producing a transparent placeholder that QML regarded as ready, allowing a blank image to be exported without an error.

This explains the separate encodability state and disabled QR actions while retaining the complete textual request. The same historical assignment distinguished thread-bound Qt capture from background image-file work, so moving disk I/O does not imply moving every Qt image operation.

Source 1 · Source 2

Ralph's inferences

A shared GUI unlock session extends the older temporary-unlock convention across overlapping application operations: ownership must cover checking the lock state, using the unlocked wallet and restoring its prior state, not merely the individual unlock call.

Pinned Core's UnlockContext records whether the wallet was initially locked and relocks on destruction. The head QML helper adds a session held from the initial check through relocking, and Receive acquires it before cs_wallet. It is therefore reasonable to interpret serialization as preserving temporary authorization semantics when formerly sequential GUI actions overlap with worker tasks. This explanation is inferred from the code and historical precedents, not an inspected original proposal for this exact session design.

Source 1

The snapshot introduces a presentation-cache boundary rather than removing backend locking or guaranteeing instantaneous state. Its design accepts bounded staleness while retaining reconciliation paths for changes not represented by ordinary wallet notifications.

The base balance and available-balance getters query Core directly. The head declares owned snapshot values for publication on the model thread, tracks notification coverage, and polls wallet progress, coin locks and outstanding payments. Pinned getAvailableBalance still locks the wallet and performs coin-selection-related work. These premises explain the combination of cached getters, worker queries and polling without establishing the correctness of every refresh path.

Unresolved disagreements

The inspected historical record presents competing migration strategies for blocking GUI calls: continuation-style asynchronous requests require restructuring existing control flow, while nested event loops can preserve that flow but complicate parallel operation ordering and object lifetime. Participants differed over whether nested loops were useful; the retrieved discussion does not establish a final universal resolution.

This tradeoff explains the significance of queued completions and explicit lifetime handling in the affected executor and models. It is historical context for the architecture, not an objection to this PR or proof that its callbacks are reentrancy-safe.

Source 1 · Source 2 · Source 3 · Source 4