WIP: qt: refactor QML frontend onto owned models

bitcoin-core/gui-qml: PR #1142

14 minor findings · 4 suggestions

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

Findings

Link

[minor] · Signed app-created drafts still export as PSBT v2

The version-0 export fix covers unsigned drafts only; saving an app-created draft after Sign only or external-signer approval still writes v2, which Core 31 and older reject.

Location: qml/walletsend.cpp:253 (head).

Details and suggested fix

ExecuteSignOnly and external approval construct PartiallySignedTransaction{unsigned_tx, 2} when the draft has no document. Their signed document becomes the review's PSBT. A subsequent Save finds that document and calls startPsbtFileExport directly, bypassing ExportReview and its version-0 construction. Thus signing a share before saving it for a cosigner changes the file's compatibility. Choose the file-export version from the review's origin: export a v0 copy of app-created drafts while retaining their signatures, preserve imported documents' versions, and leave external-signer handoff unchanged. Add a regression that signs a new draft, saves it and checks the exported version.


Link

[minor] · Timer polls restart unfinished receipt rechecks

With more than 128 unconfirmed receipts and consistently slower-than-one-second batches, timer polls repeatedly restart the recheck cursor and prevent Receive reconciliation from finishing.

Location: qml/walletreceipts.cpp:439 (head).

Details and suggested fix

Reader::publish sets needs_poll even for Pending publications, so ReceiptReconciliationModel keeps its one-second timer running during a batch. Reader::poll records another poll while work is active. The next plan consumes it and calls restartRechecks, clearing the cursor before reading another batch of at most 128 IDs. If the leading receipts remain unconfirmed and each batch overlaps a poll, the tail is never checked and Receive retains its previous reconciled totals. This source-based scenario was not reproduced at runtime; it can recover when batches become faster or the unconfirmed set shrinks. Coalesce timer polls without restarting an unfinished recheck, and test a poll before each batch completes.


Link

[minor] · Sign only bypasses the broadcast-readiness assessment

An imported PSBT completed by Sign only can say “Ready to broadcast” based on signature completeness, then be refused on Broadcast because it is non-final or below the node's relay-fee requirement.

Location: qml/models/walletsendhandle.cpp:513 (head).

Details and suggested fix

finishSendWork installs the signed document and calls review->setCanBroadcast(m_node && !result->partial). It does not run the policy assessment used by Inspect for an already-complete imported PSBT; invalidateImportReview only replaces the current-review token. The review therefore presents signature completeness as node readiness. Broadcast still re-evaluates policy and refuses the transaction, so this does not bypass admission checks. After a clean Sign only, run the same readiness assessment used for complete imports before enabling broadcast, or distinguish unassessed completeness from readiness.


Link

[minor] · Receive keeps hiding a type after its descriptor is imported

Once a receive type is refused, importing an active descriptor for that type does not restore its Receive option until the wallet is reopened.

Location: qml/walletopening.cpp:540 (head).

Details and suggested fix

markReceiveTypeUnavailable only inserts into the session cache, and both preferred-type selection and published metadata continue using that set. The handleCanGetAddressesChanged callback merely calls ingress(0), so it republishes the refusal rather than invalidating it. Pinned Core's LoadActiveScriptPubKeyMan emits this notification when a descriptor becomes active. A type tried automatically before fallback can therefore remain hidden after a console import makes it usable. Clear or re-probe cached refusals on the capability notification, and test a refusal followed by importing that type's active descriptor.


Link

[minor] · Console labels sole-wallet fallback commands as walletless

When no wallet is selected and exactly one is loaded, wallet RPCs execute in that wallet but the console labels and records their target as a node context.

Location: qml/components/SettingsView.qml:40 (head).

Details and suggested fix

DesktopWallets supplies activeWalletRpcContext: false when there is no active selection. The executor consequently sends an empty wallet URI, which pinned Core resolves through GetDefaultWallet when exactly one wallet is loaded. The console nevertheless reports “Executing command without any wallet”. This becomes reachable after console or external wallet loading because adoption no longer selects the wallet, while base did. Preserve the intended protection against retargeting an existing selection, but resolve, display and record the sole-wallet fallback consistently when no wallet was selected. Cover loading one wallet from an initially walletless console.


Link

[minor] · Reuse filtering can leave same-address outputs unavailable to Send

With avoid_reuse enabled but partial-spend avoidance disabled, Send can leave same-address outputs behind and subsequently exclude them as dirty from its balance and maximum.

Location: qml/models/coinselection.h:33 (head).

Details and suggested fix

ApplyInputPolicy sets m_avoid_address_reuse but does not enable m_avoid_partial_spends, unlike pinned sendtoaddress. Core may try a grouped alternative, but keeps the ungrouped transaction when grouping exceeds m_max_aps_fee. Spending only some outputs then marks their address used, so the remaining outputs fall under the GUI's reuse filter. They remain in the wallet and can be spent through RPC with reuse avoidance disabled. Enable partial-spend avoidance when the wallet's reuse policy applies, rather than enabling grouping unconditionally for ordinary wallets, and test two outputs at one address where grouping costs an additional fee.


Link

[minor] · Activity does not restore its position after reattaching the model

Hiding Activity detaches its model without saving a scroll anchor, so returning from details or another tab can lose the user's position; the rendered behavior was not checked.

Location: qml/pages/wallet/ActivityListPage.qml:407 (head).

Details and suggested fix

model: root.visible ? activityFilterProxy : null replaces the previous permanently attached model. Opening transaction details or switching away hides the Activity page; returning attaches the model again and rebuilds its view state. heldContentY only covers proxy moves, resets and layout changes, and expires after 400 ms, so it does not preserve position across this model swap. Keep the intended hidden-page detachment, but capture a stable row identity and offset before detaching and restore them after layout. Test both list-to-details-to-Back and switching away from a scrolled Activity tab.


Link

[minor] · Activity's position hold overwrites its final clamp

When content shrinks below the held position, onContentYChanged restores the unclamped value during the timer's final clamp; a later Qt correction was not checked in a rendered view.

Location: qml/pages/wallet/ActivityListPage.qml:383 (head).

Details and suggested fix

The timer runs restorePosition(true) before setting heldContentY = NaN. Assigning the clamped contentY synchronously invokes onContentYChanged: restorePosition(false) while the hold still contains the old value, so that handler writes the out-of-range position back. A confirmation that removes a section header near the bottom can trigger this path. Compute the clamped target, clear heldContentY, and only then assign contentY. Add a case where content shrinks while a bottom position is held.


Link

[minor] · A definite fee-bump rejection becomes an unresettable uncertain attempt

A narrow, unobserved eligibility race can make commitBumpTransaction return false before any commit, but the GUI treats that definite failure as Uncertain and refuses reset.

Location: qml/walletbump.cpp:205 (head).

Details and suggested fix

If the original confirms, gains a descendant or is replaced after the app's last check, pinned Core's final precondition check returns non-OK before calling wallet.CommitTransaction. walletbump::Execute maps the resulting false return to Error::Commit, and publishCommit maps that to Phase::Uncertain. Both re-preparation and reset refuse that state, while outcome rechecking only changes its message. Base treated the false return as a failed operation. Map a definite false return to Failed or NeedsRevalidation; retain Uncertain for exceptions where the effect boundary really is unknown.


Link

[minor] · Device approval stalls other wallets' Core-lane work

A hardware-device approval occupies the single shared Core worker, delaying other wallets' reads, Receive address generation and receipt batches despite the separate Signer worker.

Location: qml/executor.cpp:82 (head).

Details and suggested fix

Workers routes every Lane::Core post to one worker. Session::read and Session::perform use that lane, and ApprovalOwner::request invokes ApproveInto through perform. Its synchronous external-signing call therefore occupies the worker for the device wait, not merely wallet A's lock, so unrelated work for wallet B queues behind it while the GUI event loop remains responsive. Isolate device waits on the dedicated signer worker while retaining per-wallet ordering, captured review identity and action leases. Add a test that holds one wallet's approval while another wallet creates a receiving address.


Link

[minor] · Silent passphrase rewriting breaks the paste-again unlock path

New-passphrase fields silently remove CR/LF, but unlocking preserves them, so re-pasting the same clipboard fails even though the visible password matches.

Location: qml/controls/PasswordTextField.qml:20 (head).

Details and suggested fix

With dropsLineEndings enabled, pasting secret\n into the new and confirmation fields stores secret. The unlock prompt deliberately preserves the original bytes, so pasting that same clipboard submits secret\n and reports an incorrect password. Before this change, paste-and-paste worked while typing the visible text failed; the change reverses that behavior without explaining the transformation. Reject line endings visibly in new-passphrase fields instead of silently removing them. Keep existing-wallet unlock fields exact so wallets already encrypted with those bytes remain accessible.


Link

[minor] · Cancelled clipboard checks accumulate as child QObjects

With a non-empty clipboard, recipient edits repeatedly replace clipboard-check operations, but the cancelled objects remain children of SendImportModel until the page is destroyed.

Location: qml/models/sendimportmodel.cpp:50 (head).

Details and suggested fix

recipientEdited calls checkClipboard, which disconnects and cancels the previous check before requesting another operation owned by this. requestImportText forwards into createImport, which allocates a new parent-owned PaymentImportOperation. Its cancel and close release backend ownership and snapshots but never delete the QObject. The same discard pattern appears in cancelImport and cancelAll, so editing a long-lived Send page grows its child-object inventory. Schedule discarded operations for deletion after cancellation and disconnection, and test that repeated recipient edits leave a bounded child count.


Link

[minor] · The explicit macOS worker-stack safeguard was removed

The refactor replaces the explicit 8 MiB macOS worker-stack setting with default std::thread stacks; no resulting overflow has been reproduced.

Location: qml/executor.cpp:26 (head).

Details and suggested fix

Base BackendExecutor set an 8 MiB stack under Q_OS_MACOS, documenting that Core startup can exceed macOS's smaller secondary-thread default, particularly in RandAddStaticEnv under sanitizers. The new Worker and QmlInitExecutor construct plain std::thread instances without corresponding stack configuration. Actual stack requirements depend on compiler and sanitizer settings, and this platform-specific consequence remains unobserved. Preserve the documented headroom through a shared macOS thread-creation helper, or establish that the relevant Core work no longer needs it.


Link

[minor] · New payment-import errors bypass translation

File/path, unsupported-source and malformed-PSBT errors created in paymentimport remain English because they bypass translation; the previous malformed-PSBT check used tr().

Location: qml/paymentimport.cpp:101 (head).

Details and suggested fix

ReadSource creates these error messages with QStringLiteral, and AnalyzeSource does the same for its own fallback errors. They reach SendImportModel::status as display-ready text without a translation lookup, so adding catalog translations cannot localize them. Return typed errors for translation in PaymentImportOperation, or use a fixed QCoreApplication::translate context at construction, then update the catalogs. Errors already translated by downstream helpers need not be translated again.


Optional improvements

Link

[suggestion] · importdescriptors private keys remain visible in console history

The pre-existing importdescriptors redaction gap remains: descriptors carrying private keys can still appear in echoed requests and Up-arrow history.

Location: qml/models/rpccommandexecutor.cpp:28 (head).

Details and suggested fix

HISTORY_FILTER omits importdescriptors, while the console publishes prepared->filtered() as both the request row and recall history. Truncating that representation to 4096 characters does not conceal an xprv or WIF key within it. Redact arguments for descriptor imports carrying private keys and add an xprv regression, keeping the original execution arguments intact. This recommendation concerns session-visible request retention, not an established new disclosure path introduced by the refactor.


Link

[suggestion] · Speed Up omits Send's reuse-avoidance policy

Speed Up can add a dirty output when a replacement needs another input, despite Send now honoring avoid_reuse; this inconsistency also existed at base.

Location: qml/walletbump.cpp:106 (head).

Details and suggested fix

walletbump::Prepare constructs its CCoinControl without m_avoid_address_reuse, unlike coinselection::ApplyInputPolicy. Pinned Core's fee bumper permits additional confirmed inputs, and a false reuse flag allows used-address outputs even when the wallet opted into avoid_reuse. Apply the wallet's policy to replacement input selection, including partial-spend avoidance where appropriate, while preserving the required original inputs. Add a fee-bump case with both dirty and clean candidates for the extra input.


Link

[suggestion] · Captured passphrase text is released without cleansing

secretinput::Input retains a plaintext QString until native work runs, then frees it uncleansed even though its temporary UTF-8 conversion is wiped.

Location: qml/secretinput.h:34 (head).

Details and suggested fix

Input stores const QString m_text and has no cleansing destructor. materialize wipes its local QByteArray, but not the retained UTF-16 allocation. Make the retained member mutable internally and cleanse that allocation during retirement when it is uniquely owned, checking isDetached() rather than modifying shared Qt data. This reduces residual app-controlled plaintext without changing the native conversion or cleanup-thread contract. It is memory hardening, not a guarantee about other copies QML may retain.


Link

[suggestion] · Coin-row ordering duplicates the existing IndexedSequence implementation

CoinsListModel::Rows maintains a second, nearly identical indexed AVL implementation even though IndexedSequence already provides its ordering and rank operations.

Location: qml/models/coinslistmodel.cpp:51 (head).

Details and suggested fix

Rows repeats rotations, balancing, indexed insertion and removal, successor extraction, row lookup and parent-pointer rank. IndexedSequence supplies the same operations through insertAt, takeAt, indexOf and operator[]. Use an IndexedSequence of stable coin slots with a separate id-to-slot map, so payload updates do not mutate indexed keys. This removes the duplicate ordering algorithm while preserving logarithmic bookkeeping, shared coin payloads and the existing Qt begin/end row notifications and persistent-index tests.


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

GUI responsiveness historically took precedence over immediately refreshing wallet information. Replacing nonblocking polling with notifications could still freeze the interface if notification handlers acquired contended backend locks.

In bitcoin/bitcoin#10251, maintainers explained that the existing Qt timer used TRY_LOCK, whereas notification-triggered balance getters could repeatedly wait for wallet and chain locks during synchronization. This explains the motivation for moving reads behind background owners rather than merely changing signals. The pinned interface still distinguishes blocking getters from tryGetTxStatus and tryGetBalances.

Source 1 · Source 2

Background execution needs an explicit outcome and lifetime contract; moving a closure off the GUI thread alone does not settle cancellation, shutdown or resource ownership.

The earlier application issue #1054 identified silently rejected submissions, pending state without completion, missed drain notifications and undefined lifetimes for borrowed objects. Its successor #1109 proposed queued task outcomes, cancellation and destruction-surviving drain callbacks. Separately, #966 required retaining wallet resources until outstanding work and removal finish. These are direct antecedents of owned operations and shutdown draining.

Source 1 · Source 2 · Source 3

PSBT exists to separate transaction construction from signing across different software and offline devices, without requiring private keys or direct UTXO-set access at the constructing client.

BIP174 explicitly motivates a standard, extensible format for multiple signers and air-gapped or hardware wallets. Thus inspection, export, signing and broadcast are distinct workflow capabilities; a wallet unable to sign locally can still participate through PSBT exchange. The affected review path separately represents signing capability, owned inputs and broadcast capability.

Source 1

Input metadata sufficient to describe a PSBT is not automatically sufficient to trust its displayed fee. Historical multi-input SegWit fee-overpayment attacks motivated supplying full previous transactions even where witness UTXOs were available.

The 2020 BIP174 clarification allowed both UTXO forms specifically in response to that attack class. At the comparison base, the GUI displayed node::AnalyzePSBT's fee; the pinned analyzer calculates it from GetUTXO results. The new application fee proof instead checks previous-transaction identity or independently obtained outputs and binds the result to the reviewed transaction. The history explains why fee authentication is a separate concern from displaying PSBT analysis.

Source 1

External signing must preserve the transaction being authorized, but response validation is not a sandbox against malicious helper software running as the same user.

Upstream proposal #36114 explicitly tests dropped outputs, reduced values and changed scripts, and proposes merging signer responses rather than replacing the request. It also explicitly disclaims protection against a malicious same-user HWI process. The pinned Core signer currently replaces the PSBT with the decoded response; the application adds unsigned-transaction comparison. This history establishes both the motivation and the limits of those checks.

Source 1

PSBT file compatibility and external-signer handoff have historically been treated as different version-policy decisions.

Issue #36518 reported that GUI-created v2 files broke pre-v32 cosigner workflows. In #36539, the proposed version selector was dropped to simplify backporting across translation string freeze, and GUI file output moved toward v0. A separate discussion favored consistent v2 external-signer requests, followed by an author update adopting that distinction. This explains the tradeoff behind changing new file exports without necessarily changing signer handoff.

Source 1 · Source 2 · Source 3 · Source 4 · Source 5

Closing a wallet on a pruned node trades ongoing wallet synchronization for a possible future full-chain download; an intact wallet backup does not supply missing historical blocks.

Earlier application issue #1127 documents reopening failure after pruning past a closed wallet's synchronization point, while wallets left open continued tracking the chain. It distinguishes unavailable scan history from wallet-file damage and cites Bitcoin-Qt's advance warning. That explains why Close wallet confirmation conveys a consequence beyond merely hiding or unloading a wallet.

Source 1

Ralph's inferences

Binding operations to wallet and review objects separates user authorization from whichever wallet or draft happens to be visible when delayed work completes.

The head architecture specifies one wallet per page lifetime and captured operation identity. SendTransactionReview binds a controller to the wallet review interface; the controller records the review object and cancels prompts when that review changes. This is a code-based explanation of the ownership design, not a claim that historical discussion settled every stale-result case.

Cancellation of presentation and completion of an accepted effect are necessarily different events.

OwnedWork explicitly permits GUI packets to be dropped while accepted effects and cleanup continue, and its ledger tracks completion before borrowed interfaces can be released. The unchanged Core wallet interface also returns no receipt from commitTransaction. These boundaries explain why closing a page cannot by itself establish that work was undone or that a transaction was successfully submitted.

Unresolved disagreements

The historical record inspected does not establish a universal prohibition on nested event loops: participants weighed lower migration cost against ordering, reentrancy and lifetime hazards.

In #10504, one position rejected nested loops for these operations; another defended them when they improved responsiveness without rewriting existing control flow, while still preferring asynchronous event-driven GUI code generally. A further comment described escaped stack-local pointers. This matters to distinguishing ordinary background operations from event-processing waits during shutdown, but the discussion alone does not determine correctness of the present design.

Source 1 · Source 2 · Source 3 · Source 4