ralph

Outcomes

What happened to findings after review.

Addressed after review

Best-effort automated assessment of whether later PR updates addressed findings from previous reviews. This is not a causal claim or human validation.

477 assessed findings from 477 published findings across 104 source reviews.

StatusFindings
addressed221
partially_addressed15
still_present105
unclear136

Assessment jobs: 69

Assessment usage: 137 request records; 7,038,937 (partial) input tokens; 112,194 (partial) output tokens.

Finding assessments

PRFindingOutcomeEvidence
gui#1142A rejected fee-bump commit is incorrectly reported as Uncertainqml/walletbump.cppstill_present
Assessment

A false commitBumpTransaction result is still mapped to Error::Commit, and the excerpt provides no change to the reported downstream Uncertain handling.

new_source: qml/walletbump.cpp

[
  {
    "bounded": true,
    "end_line": 228,
    "evidence_id": "5c1f6da878e24a62acb331d92481af5d",
    "finding_id": "finding:9",
    "kind": "new_source",
    "line": 176,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/walletbump.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "        bool signed_replacement{false};\n        try { signed_replacement = wallet.signBumpTransaction(signed_tx); } catch (...) {}\n        if (!signed_replacement) { result.error = Error::Sign; return finishAfterRelock(); }\n        if (!MatchesUnsignedTransaction(review.transaction, signed_tx)) { result.error = Error::Changed; return finishAfterRelock(); }\n        if (wallet.hasExternalSigner() && !walletsend::VerifyExternalTransaction(wallet, CTransaction{signed_tx})) {\n            result.error = Error::InvalidSignature; return finishAfterRelock();\n        }\n        if (const auto scope_error = CheckApprovedScope(wallet, review); scope_error != Error::None) {\n            result.error = scope_error; return finishAfterRelock();\n        }\n        // No further key operation is needed. Restore authorization before\n        // commit, and never publish a successful spend with failed restoration.\n        restoreWalletLock(); passphrase.reset();\n        if (result.relock_failed) return result;\n        if (services.admission) {\n            const auto exact = MakeTransactionRef(signed_tx);\n            const auto decision = psbtpolicy::Evaluate(services.admission(exact, review.new_fee));\n            if (decision.state == psbtpolicy::State::Blocked) {\n                result.error = Error::Policy;\n                result.message = decision.explanation;\n                return result;\n            }\n        }\n        std::vector<bilingual_str> errors;\n        Txid txid;\n        const CTransaction exact{signed_tx};\n        result.candidate_txid = exact.GetHash();\n        result.candidate_wtxid = exact.GetWitnessHash();\n        result.commit_attempted = true;\n        if (!wallet.commitBumpTransaction(review.original, std::move(signed_tx), errors, txid)) {\n            result.error = Error::Commit; result.message = Message(errors); return result;\n        }\n        result.txid = txid;\n        result.committed = true;\n        Observe(wallet, result);\n    } catch (const secretinput::Failure&) {\n        result.error = Error::Invalid; result.message = QObject::tr(\"The wallet password could not be prepared. No fee bump was submitted.\");\n    } catch (...) { result.error = Error::Uncertain; }\n    return finishAfterRelock();\n}\nCommit ObserveOutcome(interfaces::Wallet& wallet, const Commit& original)\n{\n    auto result = original;\n    result.record = Record::Unknown;\n    result.submission = Submission::Unknown;\n    if (!original.commit_attempted || original.candidate_txid == Txid{}) return result;\n    result.txid = original.candidate_txid;\n    Observe(wallet, result, true);\n    // Observing a record cannot manufacture the original call's missing\n    // persistence/replacement-metadata receipt. Keep its uncertainty explicit.\n    return result;\n}\n} // namespace walletbump",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142The Receive editor no longer offers Copy addressqml/components/ReceiveEditorFields.qmladdressed
Assessment

ReceiveEditorFields now provides a visible Copy address button when an address is present, with a clipboard action; the new test exercises copying.

path_diff: qml/components/ReceiveEditorFields.qml; new_source: qml/components/ReceiveEditorFields.qml

[
  {
    "evidence_id": "a10be1e5d14b40d8a4b7de6ec6373295",
    "finding_id": "finding:8",
    "kind": "path_diff",
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/components/ReceiveEditorFields.qml",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "diff --git a/qml/components/ReceiveEditorFields.qml b/qml/components/ReceiveEditorFields.qml\nindex 2a367a0fc6..a1b8eb5339 100644\n--- a/qml/components/ReceiveEditorFields.qml\n+++ b/qml/components/ReceiveEditorFields.qml\n@@ -17,7 +17,22 @@ ColumnLayout {\n         value: ApplicationModels.optionsModel.displayUnit\n         when: root.editor !== null\n     }\n-    CoreText { Layout.fillWidth: true; text: root.editor ? root.editor.address : \"\"; wrapMode: Text.WrapAnywhere }\n+    RowLayout {\n+        Layout.fillWidth: true\n+        spacing: 8\n+        CoreText {\n+            objectName: \"receiveEditorAddressText\"\n+            Layout.fillWidth: true\n+            text: root.editor ? root.editor.address : \"\"\n+            wrapMode: Text.WrapAnywhere\n+        }\n+        NeutralButton {\n+            objectName: \"receiveCopyAddressButton\"\n+            text: qsTr(\"Copy address\")\n+            visible: root.editor !== null && root.editor.address.length > 0\n+            onClicked: Clipboard.setText(root.editor.address)\n+        }\n+    }\n     CoreText {\n         Layout.fillWidth: true\n         visible: root.editor !== null && root.editor.historicallyUsed\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 111,
    "evidence_id": "21151147f8a64f1baec9d2c211705e10",
    "finding_id": "finding:8",
    "kind": "new_source",
    "line": 1,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/components/ReceiveEditorFields.qml",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "// Copyright (c) 2026 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\nimport QtQuick 2.15\nimport QtQml 2.15\nimport QtQuick.Layouts 1.15\nimport org.bitcoincore.qt 1.0\nimport \"../controls\"\n\nColumnLayout {\n    id: root\n    required property PaymentRequestEditorModel editor\n    spacing: 16\n    Binding {\n        target: root.editor ? root.editor.amount : null\n        property: \"unit\"\n        value: ApplicationModels.optionsModel.displayUnit\n        when: root.editor !== null\n    }\n    RowLayout {\n        Layout.fillWidth: true\n        spacing: 8\n        CoreText {\n            objectName: \"receiveEditorAddressText\"\n            Layout.fillWidth: true\n            text: root.editor ? root.editor.address : \"\"\n            wrapMode: Text.WrapAnywhere\n        }\n        NeutralButton {\n            objectName: \"receiveCopyAddressButton\"\n            text: qsTr(\"Copy address\")\n            visible: root.editor !== null && root.editor.address.length > 0\n            onClicked: Clipboard.setText(root.editor.address)\n        }\n    }\n    CoreText {\n        Layout.fillWidth: true\n        visible: root.editor !== null && root.editor.historicallyUsed\n        text: qsTr(\"This address has been used. Public payment details are read only; the private note can still be edited.\")\n    }\n    BitcoinAmountInputField {\n        amount: root.editor ? root.editor.amount : null\n        readOnly: root.editor === null || !root.editor.publicFieldsEditable || root.editor.busy\n        inputObjectName: \"receiveAmountInput\"\n        unitToggleObjectName: \"receiveAmountUnitButton\"\n    }\n    TextFieldRow {\n        Layout.fillWidth: true\n        title: qsTr(\"Recipient name\")\n        fieldObjectName: \"receivePublicLabelInput\"\n        textInput: root.editor ? root.editor.publicLabel : null\n        maximumLength: 16384\n        readOnly: root.editor === null || !root.editor.publicFieldsEditable || root.editor.busy\n    }\n    TextFieldRow {\n        Layout.fillWidth: true\n        title: qsTr(\"Public message\")\n        fieldObjectName: \"receiveMessageInput\"\n        textInput: root.editor ? root.editor.message : null\n        maximumLength: 16384\n        readOnly: root.editor === null || !root.editor.publicFieldsEditable || root.editor.busy\n    }\n    TextFieldRow {\n        Layout.fillWidth: true\n        title: qsTr(\"Note to self\")\n        fieldObjectName: \"receivePrivateNoteInput\"\n        textInput: root.editor ? root.editor.privateNote : null\n        maximumLength: 16384\n        readOnly: root.editor === null || !root.editor.available || root.editor.busy\n    }\n    Repeater {\n        model: root.editor ? root.editor.conflicts : []\n        delegate: RowLayout {\n            id: conflictRow\n            required property var modelData\n            CoreText { Layout.fillWidth: true; text: conflictRow.modelData.fieldId + \": \" + conflictRow.modelData.committedText }\n            NeutralButton {\n                text: qsTr(\"Use current\")\n                onClicked: root.editor.resolveConflict(conflictRow.modelData.fieldId, TextEditSessionModel.UseCurrent)\n            }\n            NeutralButton {\n                text: qsTr(\"Keep edit\")\n                enabled: root.editor !== null && (root.editor.publicFieldsEditable || conflictRow.modelData.fieldId === \"note\")\n                onClicked: root.editor.resolveConflict(conflictRow.modelData.fieldId, TextEditSessionModel.KeepEdit)\n            }\n        }\n    }\n    CoreText {\n        objectName: \"receiveEditorError\"\n        Layout.fillWidth: true\n        visible: text.length > 0\n        text: root.editor ? root.editor.error.message : \"\"\n        color: Theme.color.dangerText\n    }\n    RowLayout {\n        PrimaryButton {\n            objectName: \"receiveSaveRequestButton\"\n            text: root.editor && root.editor.mutationKind === PaymentRequestEditorModel.Create ? qsTr(\"Create request\") : qsTr(\"Update request\")\n            enabled: root.editor !== null && root.editor.canSave\n            busy: root.editor !== null && root.editor.busy\n            onClicked: root.editor.save()\n        }\n        NeutralButton {\n            objectName: \"receiveDiscardEditsButton\"\n            text: qsTr(\"Discard edits\")\n            enabled: root.editor !== null && root.editor.canDiscard\n            onClicked: root.editor.discard()\n        }\n    }\n    ReceiveEditorCloseQuestion { Layout.fillWidth: true; editor: root.editor }\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142Close leaves the inline Receive editor visible but unusableqml/components/ReceiveRequestEditorCard.qmladdressed
Assessment

The inline ReceivePage now sets closable: false, hiding the Close button for the affected inline editor. The card retains the button for other contexts.

path_diff: qml/components/ReceiveRequestEditorCard.qml; new_source: qml/components/ReceiveRequestEditorCard.qml

[
  {
    "evidence_id": "071783efc44849389c1c32ae387158d5",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/components/ReceiveRequestEditorCard.qml",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "diff --git a/qml/components/ReceiveRequestEditorCard.qml b/qml/components/ReceiveRequestEditorCard.qml\nindex 1d0b30a9e5..f0af8be559 100644\n--- a/qml/components/ReceiveRequestEditorCard.qml\n+++ b/qml/components/ReceiveRequestEditorCard.qml\n@@ -21,6 +21,7 @@ Pane {\n     // A question belongs to the request it was asked about.\n     onEditorChanged: deletion.reset()\n     property bool viewActive: true\n+    property bool closable: true\n     readonly property RequestSharingModel sharing: receive && editor && editor.requestId.length > 0 ? receive.sharing(editor, root) : null\n     signal closeRequested()\n     signal requestAgain(string id)\n@@ -93,7 +94,7 @@ Pane {\n         }\n         ReceiveEditorCloseQuestion { Layout.fillWidth: true; editor: root.deleteEditor }\n         CoreText { Layout.fillWidth: true; text: deletion.error; visible: text.length > 0; color: Theme.color.dangerText }\n-        NeutralButton { objectName: \"savedRequestCloseButton\"; text: qsTr(\"Close\"); enabled: root.editor !== null; onClicked: root.editor.requestClose() }\n+        NeutralButton { objectName: \"savedRequestCloseButton\"; visible: root.closable; text: qsTr(\"Close\"); enabled: root.editor !== null; onClicked: root.editor.requestClose() }\n     }\n     Connections {\n         target: root.editor\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 103,
    "evidence_id": "d46a394d36764fd484d9ccacc003f644",
    "finding_id": "finding:7",
    "kind": "new_source",
    "line": 66,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/components/ReceiveRequestEditorCard.qml",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "        // A different editor identity destroys the old native text/undo\n        // context. Amount canonical state remains in that editor's model.\n        Repeater {\n            model: root.editor ? [root.editor] : []\n            delegate: ReceiveEditorFields {\n                required property PaymentRequestEditorModel modelData\n                Layout.fillWidth: true\n                editor: modelData\n            }\n        }\n        Repeater {\n            model: root.sharing ? [root.sharing] : []\n            delegate: SavedRequestSharing {\n                required property RequestSharingModel modelData\n                Layout.fillWidth: true\n                sharing: modelData\n                interested: root.viewActive && root.visible\n            }\n        }\n        RowLayout {\n            visible: root.editor !== null && root.editor.requestId.length > 0\n            NeutralButton { objectName: \"savedRequestAgainButton\"; text: qsTr(\"Request again\"); onClicked: root.requestAgain(root.editor.requestId) }\n            NeutralButton {\n                objectName: \"savedRequestDeleteButton\"\n                text: qsTr(\"Delete request\")\n                enabled: root.receive !== null && root.editor !== null && !root.editor.busy && root.deleteEditor === null\n                onClicked: deletion.request(root.editor.requestId)\n            }\n        }\n        ReceiveEditorCloseQuestion { Layout.fillWidth: true; editor: root.deleteEditor }\n        CoreText { Layout.fillWidth: true; text: deletion.error; visible: text.length > 0; color: Theme.color.dangerText }\n        NeutralButton { objectName: \"savedRequestCloseButton\"; visible: root.closable; text: qsTr(\"Close\"); enabled: root.editor !== null; onClicked: root.editor.requestClose() }\n    }\n    Connections {\n        target: root.editor\n        function onClosed(editorId) { if (root.editor && editorId === root.editor.editorId) root.closeRequested() }\n    }\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142The macOS Core-thread stack safeguard was droppedqml/executor.cppstill_present
Assessment

The new Worker still constructs its thread with plain std::thread; the supplied new-head excerpt shows no macOS-specific stack-size safeguard.

new_source: qml/executor.cpp

[
  {
    "bounded": true,
    "end_line": 150,
    "evidence_id": "eca9704c37574701855d31ed1a7815ba",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 1,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/executor.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "// Copyright (c) 2026 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <qml/executor.h>\n\n#include <qml/execution.h>\n\n#include <algorithm>\n#include <atomic>\n#include <cassert>\n#include <condition_variable>\n#include <deque>\n#include <mutex>\n#include <thread>\n#include <utility>\n#include <vector>\n\nnamespace execution {\nnamespace {\nusing Callback = std::function<void()>;\n\nclass Worker\n{\npublic:\n    Worker() : m_thread([this] { run(); }) {}\n    ~Worker()\n    {\n        close();\n        join();\n    }\n\n    bool post(Callback callback)\n    {\n        {\n            std::lock_guard lock{m_mutex};\n            if (m_closed) return false;\n            m_tasks.push_back(std::move(callback));\n        }\n        m_ready.notify_one();\n        return true;\n    }\n\n    void close()\n    {\n        {\n            std::lock_guard lock{m_mutex};\n            m_closed = true;\n        }\n        m_ready.notify_one();\n    }\n\n    void join()\n    {\n        if (m_thread.joinable()) m_thread.join();\n    }\n\nprivate:\n    void run()\n    {\n        for (;;) {\n            Callback callback;\n            {\n                std::unique_lock lock{m_mutex};\n                m_ready.wait(lock, [this] { return m_closed || !m_tasks.empty(); });\n                if (m_tasks.empty()) return;\n                callback.swap(m_tasks.front());\n                m_tasks.pop_front();\n            }\n            callback();\n        }\n    }\n\n    std::mutex m_mutex;\n    std::condition_variable m_ready;\n    std::deque<Callback> m_tasks;\n    bool m_closed{false};\n    std::thread m_thread;\n};\n\nstruct Workers {\n    Worker core, priority, rpc, io, signer, cleanup;\n\n    bool post(Lane lane, UtilityWorker utility, Callback callback)\n    {\n        switch (lane) {\n        case Lane::Core: return core.post(std::move(callback));\n        case Lane::Priority: return priority.post(std::move(callback));\n        case Lane::Rpc: return rpc.post(std::move(callback));\n        case Lane::Utility:\n            switch (utility) {\n            case UtilityWorker::IO: return io.post(std::move(callback));\n            case UtilityWorker::Signer: return signer.post(std::move(callback));\n            case UtilityWorker::Cleanup: return cleanup.post(std::move(callback));\n            }\n            return false;\n        case Lane::Domain:\n        case Lane::Control:\n        case Lane::Cleanup: return false;\n        }\n        return false;\n    }\n\n    void stopAndJoin()\n    {\n        for (auto* worker : {&core, &priority, &rpc, &io, &signer, &cleanup}) worker->close();\n        for (auto* worker : {&core, &priority, &rpc, &io, &signer, &cleanup}) worker->join();\n    }\n};\n} // namespace\n\nstruct SerialQueue::State : std::enable_shared_from_this<SerialQueue::State> {\n    State(Executor::Dispatch dispatch, Lane lane, UtilityWorker utility)\n        : dispatch(std::move(dispatch)), lane(lane), utility(utility) {}\n\n    void run()\n    {\n        {\n            std::lock_guard lock{mutex};\n            admission = nullptr;\n        }\n        changed.notify_all();\n\n        for (;;) {\n            Callback task;\n            std::vector<Callback> ready;\n            {\n                std::lock_guard lock{mutex};\n                if (tasks.empty()) {\n                    active = false;\n                    ready = takeListeners();\n                } else {\n                    task.swap(tasks.front());\n                    tasks.pop_front();\n                }\n            }\n            if (!task) {\n                changed.notify_all();\n                notify(std::move(ready));\n                return;\n            }\n            // Destroy captures before the next idle check, outside the mutex.\n            task();\n            task = {};\n            {\n                std::lock_guard lock{mutex};\n                if (tasks.empty()) continue;\n            }\n            // An inline dispatcher resumes this loop without growing the stack.\n            static thread_local State* posting{};",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142PSBT file import rejects files above 4 MiB that export permitsqml/paymentimport.cppaddressed
Assessment

The new head changes MAX_FILE from 4 MiB to MAX_FILE_SIZE_PSBT, removing the reported 4 MiB file-input ceiling.

path_diff: qml/paymentimport.cpp; new_source: qml/paymentimport.cpp

[
  {
    "evidence_id": "66834bd5e065438e8ce839f381a913e7",
    "finding_id": "finding:4",
    "kind": "path_diff",
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/paymentimport.cpp",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "diff --git a/qml/paymentimport.cpp b/qml/paymentimport.cpp\nindex f39ff5ef6a..1e2a91a7c4 100644\n--- a/qml/paymentimport.cpp\n+++ b/qml/paymentimport.cpp\n@@ -26,7 +26,7 @@\n \n namespace paymentimport {\n namespace {\n-constexpr qsizetype MAX_TEXT{1024 * 1024}, MAX_FILE{4 * 1024 * 1024};\n+constexpr qsizetype MAX_TEXT{1024 * 1024}, MAX_FILE{MAX_FILE_SIZE_PSBT};\n constexpr auto RETRY{std::chrono::milliseconds{100}};\n Inspection Invalid(const QString& error) { Inspection result; result.error = error.left(4096); return result; }\n QString PaymentIdentity(const senddraft::PaymentRequest& payment)\n@@ -132,22 +132,22 @@ struct Owner::Delivery {\n         Reply reply;\n     };\n     std::shared_ptr<Cell> cell;\n-    std::function<void()> deliver;\n+    std::shared_ptr<void> outcome;\n     ReplyKind kind;\n     std::optional<Child> child;\n     uint64_t identity{0}, source{0}, target{0};\n     void complete(Reply value)\n     {\n-        std::function<void()> notify;\n+        std::shared_ptr<void> release;\n         {\n             std::lock_guard lock{cell->mutex};\n             if (!cell->ready) {\n                 cell->reply = std::move(value);\n                 cell->ready = true;\n-                notify = std::move(deliver);\n+                release = std::move(outcome);\n             }\n         }\n-        if (notify) notify();\n+        release.reset();\n     }\n };\n struct Owner::State {\n@@ -309,7 +309,7 @@ std::shared_ptr<Owner::Delivery> Owner::reserve(ReplyKind kind, std::optional<Ch\n     };\n     auto outcome = m_outcomes->hold([take, consume] { consume(take()); });\n     if (!outcome) return {};\n-    delivery->deliver = [outcome = std::move(outcome)]() mutable { outcome.reset(); };\n+    delivery->outcome = std::move(outcome);\n     try {\n         state.deliveries.emplace(identity, delivery);\n     } catch (...) {\n@@ -490,6 +490,7 @@ execution::SubmitResult Owner::close()\n     m_presentation_allowed->store(false);\n     if (!m_close_requested.exchange(true)) {\n         auto post = std::move(m_post_close);\n+        m_post_close = {};\n         if (!post) return {{}, execution::Rejection::Closed};\n         post(shared_from_this());\n     }\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 150,
    "evidence_id": "9f09947d68b24e1d9e1fd8128f39344a",
    "finding_id": "finding:4",
    "kind": "new_source",
    "line": 1,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/paymentimport.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "// Copyright (c) 2026 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <qml/paymentimport.h>\n#include <qml/executor.h>\n#include <qml/retainedvalue.h>\n#include <qml/models/bitcoinuri.h>\n#include <qml/psbtwork.h>\n\n#include <QCryptographicHash>\n#include <QFile>\n#include <QFileInfo>\n#include <QUrl>\n#include <key_io.h>\n#include <psbt.h>\n\n#include <atomic>\n#include <algorithm>\n#include <limits>\n#include <map>\n#include <mutex>\n#include <stdexcept>\n#include <span>\n#include <utility>\n\nnamespace paymentimport {\nnamespace {\nconstexpr qsizetype MAX_TEXT{1024 * 1024}, MAX_FILE{MAX_FILE_SIZE_PSBT};\nconstexpr auto RETRY{std::chrono::milliseconds{100}};\nInspection Invalid(const QString& error) { Inspection result; result.error = error.left(4096); return result; }\nQString PaymentIdentity(const senddraft::PaymentRequest& payment)\n{\n    const auto destination = DecodeDestination(payment.address.toStdString());\n    const auto address = IsValidDestination(destination) ? QString::fromStdString(EncodeDestination(destination)) : payment.address;\n    QByteArray bytes;\n    for (const auto& field : {address, payment.amount ? QString::number(*payment.amount) : QStringLiteral(\"absent\"), payment.label, payment.message}) {\n        const auto encoded = field.toUtf8(); bytes += QByteArray::number(encoded.size()) + ':' + encoded;\n    }\n    return QString::fromLatin1(QCryptographicHash::hash(bytes, QCryptographicHash::Sha256).toHex());\n}\n}\n\nInspection ReadSource(const Input& input)\n{\n    auto kind = input.kind;\n    QString value = input.value;\n    if (kind == Input::Kind::Drop) {\n        if (input.url_count < 0 || input.url_count > 1) return Invalid(QStringLiteral(\"Drop one payment request or PSBT at a time.\"));\n        if (input.url_count == 1) value = input.url.toString();\n        kind = input.url_count == 1 && input.url.isLocalFile() ? Input::Kind::File : Input::Kind::Text;\n    } else if (kind == Input::Kind::File && !input.url.isEmpty()) {\n        value = input.url.toString();\n    }\n    QByteArray bytes;\n    QString identity_path;\n    if (kind == Input::Kind::File) {\n        const auto path = psbtwork::LocalFilePath(value);\n        if (path.isEmpty() || path.size() > 4096) return Invalid(QStringLiteral(\"The import path is invalid.\"));\n        if (!QFileInfo(path).isFile()) return Invalid(QStringLiteral(\"The import source must be a regular local file.\"));\n        QFile file{path};\n        if (!file.open(QIODevice::ReadOnly)) return Invalid(QStringLiteral(\"The import source could not be opened.\"));\n        identity_path = QFileInfo(file).canonicalFilePath();\n        if (identity_path.isEmpty()) return Invalid(QStringLiteral(\"The import file path could not be resolved.\"));\n        bytes = file.read(MAX_FILE + 1);\n        if (file.error() != QFileDevice::NoError || bytes.size() > MAX_FILE || !file.atEnd())\n            return Invalid(QStringLiteral(\"The import source is too large or could not be read.\"));\n    } else {\n        if (value.size() > MAX_TEXT) return Invalid(QStringLiteral(\"The import source is too large.\"));\n        bytes = value.toUtf8();\n    }\n    Inspection result;\n    result.field = input.field;\n    result.source_identity = QString::fromLatin1(QCryptographicHash::hash(bytes, QCryptographicHash::Sha256).toHex()) + QLatin1Char(':') +\n        QString::fromLatin1(QCryptographicHash::hash(identity_path.toUtf8(), QCryptographicHash::Sha256).toHex());\n    const auto text = QString::fromUtf8(bytes).trimmed();\n    if (text.startsWith(QStringLiteral(\"bitcoin:\"), Qt::CaseInsensitive)) {\n        const auto payment = BitcoinUri::Parse(text);\n        if (!payment.success) return Invalid(payment.error);\n        if (payment.address.size() > 1024 || payment.label.size() > senddraft::Limits::note ||\n            payment.message.size() > senddraft::Limits::message) return Invalid(QStringLiteral(\"The payment request metadata is too large.\"));\n        result.kind = Kind::Payment;\n        result.payment.address = payment.address;\n        result.payment.label = payment.label;\n        result.payment.message = payment.message;\n        if (payment.has_amount) result.payment.amount = payment.amount_sats;\n        result.payment_identity = PaymentIdentity(result.payment);\n        // Public URI fields never manufacture a user-authored private note.\n        return result;\n    }\n    const auto raw = DecodeRawPSBT(std::as_bytes(std::span{bytes.constData(), static_cast<size_t>(bytes.size())}));\n    auto document = raw ? std::optional<PartiallySignedTransaction>{*raw} : std::nullopt;\n    if (!document) {\n        const auto decoded = DecodeBase64PSBT(text.toStdString());\n        if (decoded) document = *decoded;\n    }\n    if (!document) return Invalid(QStringLiteral(\"The source is not a supported payment request or PSBT.\"));\n    const auto transaction = document->GetUnsignedTx();\n    if (!transaction || transaction->vin.empty() || transaction->vout.empty() ||\n        document->inputs.size() != transaction->vin.size() || document->outputs.size() != transaction->vout.size())\n        return Invalid(QStringLiteral(\"The PSBT is malformed.\"));\n    auto parsed = std::make_shared<psbtwork::Snapshot>();\n    parsed->document = std::make_shared<const PartiallySignedTransaction>(std::move(*document));\n    result.kind = Kind::Psbt;\n    result.psbt = std::move(parsed);\n    return result;\n}\n\nInspection AnalyzeSource(const Inspection& source, const psbtfee::Lookup& lookup)\n{\n    if (source.kind != Kind::Psbt || !source.psbt || !source.psbt->document) return Invalid(QStringLiteral(\"No PSBT is available for inspection.\"));\n    psbtwork::Request request;\n    request.kind = psbtwork::Kind::Inspect;\n    request.document = source.psbt->document;\n    psbtwork::Context context; context.lookup = lookup;\n    const auto analyzed = psbtwork::Execute(nullptr, std::move(request), context);\n    if (!analyzed.snapshot) return Invalid(analyzed.error.isEmpty() ? QStringLiteral(\"The PSBT could not be inspected.\") : analyzed.error);\n    auto result = source;\n    result.psbt = analyzed.snapshot;\n    return result;\n}\n\nstruct Owner::Reply {\n    std::optional<Target> target;\n    std::optional<ChildReply> child;\n    std::exception_ptr error;\n};\nstruct Owner::Delivery {\n    struct Cell {\n        std::mutex mutex;\n        bool ready{false};\n        Reply reply;\n    };\n    std::shared_ptr<Cell> cell;\n    std::shared_ptr<void> outcome;\n    ReplyKind kind;\n    std::optional<Child> child;\n    uint64_t identity{0}, source{0}, target{0};\n    void complete(Reply value)\n    {\n        std::shared_ptr<void> release;\n        {\n            std::lock_guard lock{cell->mutex};\n            if (!cell->ready) {\n                cell->reply = std::move(value);\n                cell->ready = true;\n                release = std::move(outcome);\n            }\n        }\n        release.reset();",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142Avoid-reuse Send can leave remaining outputs at an address unavailableqml/models/coinselection.hstill_present
Assessment

ApplyInputPolicy still sets m_avoid_address_reuse but does not enable m_avoid_partial_spends. The reported coupling is not shown as fixed.

new_source: qml/models/coinselection.h

[
  {
    "bounded": true,
    "end_line": 152,
    "evidence_id": "dc551873e57045aea375577bfde70c38",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 3,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/models/coinselection.h",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#ifndef BITCOIN_QML_MODELS_COINSELECTION_H\n#define BITCOIN_QML_MODELS_COINSELECTION_H\n\n#include <wallet/coincontrol.h>\n\n#include <algorithm>\n#include <cstdint>\n#include <functional>\n#include <iterator>\n#include <memory>\n#include <optional>\n#include <set>\n#include <utility>\n\nnamespace coinselection {\n\n// Automatic and Manual are user intent. In particular, an empty Manual\n// selection must remain empty instead of being interpreted as a request to\n// let Core choose wallet inputs.\nenum class InputMode { Automatic, Manual };\n\ninline void ApplyInputPolicy(wallet::CCoinControl& control, const InputMode mode)\n{\n    control.m_allow_other_inputs = mode == InputMode::Automatic;\n\n    // Core applies this filter only when the wallet has avoid_reuse enabled.\n    // Setting it on every app-generated control therefore preserves ordinary\n    // wallet behavior while honoring the wallet's opt-in policy.\n    control.m_avoid_address_reuse = true;\n}\n\n// Deterministic intent reducer for the temporary coin-selection editor. It\n// owns no wallet or GUI objects; the caller supplies the value-retention\n// boundary used by an opening session.\nclass Session\n{\npublic:\n    using Selection = std::set<COutPoint>;\n    using Snapshot = std::shared_ptr<const Selection>;\n    using Retain = std::function<Snapshot(Selection)>;\n    enum class Intent { Select, Unselect, Toggle, Replace, Begin, Apply, Cancel, ChooseAutomatic, ChooseManual };\n    struct Transition { Snapshot selection; std::uint64_t revision{0}; InputMode mode{InputMode::Automatic}; bool failed{false}; bool changed{false}; };\n    struct MarkChange { Snapshot marks; std::uint64_t revision{0}; bool failed{false}; };\n\n    explicit Session(Retain retain) : m_retain{std::move(retain)}\n    {\n        m_empty = m_retain({});\n        m_selection = m_marks = m_empty;\n    }\n\n    bool ready() const { return bool(m_empty); }\n    Snapshot selection() const { return m_selection; }\n    Snapshot marks() const { return m_marks; }\n    std::uint64_t revision() const { return m_revision; }\n    std::uint64_t marksRevision() const { return m_marks_revision; }\n    std::uint64_t catalogVersion() const { return m_catalog_version; }\n    InputMode inputMode() const { return m_mode; }\n    const Selection& missing() const { return m_missing; }\n    bool editing() const { return bool(m_baseline); }\n\n    Transition apply(Intent intent, std::optional<COutPoint> outpoint = {}, Snapshot replacement = {})\n    {\n        if (!ready()) return result(true, false);\n        if (intent == Intent::Begin) {\n            if (!m_baseline) m_baseline = m_selection;\n            return result(false, false);\n        }\n        if (intent == Intent::Apply) {\n            m_baseline.reset();\n            if (!m_catalog_known) return result(false, false);\n            Selection retained;\n            std::set_intersection(m_selection->begin(), m_selection->end(), m_catalog.begin(), m_catalog.end(), std::inserter(retained, retained.end()));\n            return replaceSelection(std::move(retained));\n        }\n        if (intent == Intent::Cancel) {\n            if (!m_baseline) return result(false, false);\n            auto restored = m_baseline;\n            m_baseline.reset();\n            if (restored == m_selection) return result(false, false);\n            m_selection = std::move(restored);\n            updateMissing();\n            ++m_revision;\n            return result(false, true);\n        }\n        if (intent == Intent::ChooseAutomatic || intent == Intent::ChooseManual) {\n            const auto mode = intent == Intent::ChooseManual ? InputMode::Manual : InputMode::Automatic;\n            if (m_mode == mode && (mode == InputMode::Manual || m_selection->empty())) return result(false, false);\n            if (mode == InputMode::Automatic && !m_selection->empty()) {\n                auto empty = m_retain({});\n                if (!empty) return result(true, false);\n                m_selection = std::move(empty);\n                updateMissing();\n            }\n            m_mode = mode;\n            m_baseline.reset();\n            ++m_revision;\n            return result(false, true);\n        }\n\n        Selection next;\n        if (intent == Intent::Replace) {\n            if (replacement) next = *replacement;\n        } else {\n            next = *m_selection;\n            if (outpoint) {\n                if (intent == Intent::Unselect || (intent == Intent::Toggle && next.contains(*outpoint))) next.erase(*outpoint);\n                else next.insert(*outpoint);\n            }\n        }\n        if (next == *m_selection) return result(false, false);\n        if (auto retained = m_retain(std::move(next))) {\n            m_selection = std::move(retained);\n            ++m_revision;\n            return result(false, true);\n        }\n        return result(true, false);\n    }\n\n    MarkChange toggleMark(std::optional<COutPoint> outpoint = {})\n    {\n        if (!ready()) return {m_marks, m_marks_revision, true};\n        Selection next = outpoint ? *m_marks : Selection{};\n        if (outpoint) {\n            if (next.contains(*outpoint)) next.erase(*outpoint);\n            else next.insert(*outpoint);\n        }\n        if (next == *m_marks) return {m_marks, m_marks_revision, false};\n        auto retained = m_retain(std::move(next));\n        if (!retained) return {m_marks, m_marks_revision, true};\n        m_marks = std::move(retained);\n        ++m_marks_revision;\n        return {m_marks, m_marks_revision, false};\n    }\n\n    bool reconcileCatalog(const Selection& catalog)\n    {\n        if (m_catalog_known && catalog == m_catalog) return false;\n        m_catalog = catalog;\n        m_catalog_known = true;\n        ++m_catalog_version;\n        updateMissing();\n        return true;\n    }\n\n    // Bulk marks name outputs of the current catalog only. A spent output\n    // must not keep a stale count or become a later Lock/Unlock target.\n    bool retainMarks(const Selection& catalog)\n    {",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142importdescriptors private keys remain visible in console recallqml/models/rpccommandexecutor.cppstill_present
Assessment

The new-head HISTORY_FILTER is unchanged: it still omits importdescriptors, and the comment still says “plus addhdkey.” The reported redaction gap and comment qualification remain.

new_source: qml/models/rpccommandexecutor.cpp

[
  {
    "bounded": true,
    "end_line": 150,
    "evidence_id": "a8112bdeedf041e6b7ae4963b50cf827",
    "finding_id": "finding:21",
    "kind": "new_source",
    "line": 1,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/models/rpccommandexecutor.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "// Copyright (c) 2011-2026 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n//\n// Portions of this file are ported from src/qt/rpcconsole.cpp.\n\n#include <qml/models/rpccommandexecutor.h>\n\n#include <interfaces/node.h>\n#include <rpc/client.h>\n#include <univalue.h>\n#include <util/strencodings.h>\n\n#include <cassert>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n#include <optional>\n\n#include <QStringList>\n#include <QUrl>\n#include <QCoreApplication>\n\nnamespace {\n\n// Redact arguments before storing either request output or recall history.\n// Keep the pinned Qt Widgets historyFilter policy, plus addhdkey's private key.\n// The parity regression requires an explicit review when Core's policy changes.\nconst QStringList HISTORY_FILTER = QStringList()\n    << \"addhdkey\"\n    << \"createwallet\"\n    << \"createwalletdescriptor\"\n    << \"migratewallet\"\n    << \"signmessagewithprivkey\"\n    << \"signrawtransactionwithkey\"\n    << \"walletpassphrase\"\n    << \"walletpassphrasechange\"\n    << \"encryptwallet\";\n\n} // namespace\n\nstruct RpcCommandExecutor::Plan {\n    struct Argument {\n        std::string literal;\n        std::optional<size_t> result;\n        std::vector<std::string> queries;\n    };\n    std::vector<std::vector<Argument>> calls;\n    Argument result;\n    std::string filtered;\n};\n\nconst std::string& RpcCommandExecutor::Prepared::filtered() const { return m_plan->filtered; }\n\nstd::optional<RpcCommandExecutor::Prepared> RpcCommandExecutor::Prepare(const std::string& strCommand)\n{\n    auto plan = std::make_shared<Plan>();\n    std::vector<std::vector<Plan::Argument>> stack;\n    stack.emplace_back();\n\n    enum CmdParseState {\n        STATE_EATING_SPACES,\n        STATE_EATING_SPACES_IN_ARG,\n        STATE_EATING_SPACES_IN_BRACKETS,\n        STATE_ARGUMENT,\n        STATE_SINGLEQUOTED,\n        STATE_DOUBLEQUOTED,\n        STATE_ESCAPE_OUTER,\n        STATE_ESCAPE_DOUBLEQUOTED,\n        STATE_COMMAND_EXECUTED,\n        STATE_COMMAND_EXECUTED_INNER\n    } state = STATE_EATING_SPACES;\n\n    std::string curarg;\n    Plan::Argument last_result;\n    unsigned nDepthInsideSensitive = 0;\n    size_t filter_begin_pos = 0, chpos;\n    std::vector<std::pair<size_t, size_t>> filter_ranges;\n\n    auto add_to_current_stack = [&](const std::string& strArg) {\n        if (stack.empty()) throw std::runtime_error(\"Invalid Syntax\");\n        if (stack.back().empty() && (!nDepthInsideSensitive) &&\n            HISTORY_FILTER.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) {\n            nDepthInsideSensitive = 1;\n            filter_begin_pos = chpos;\n        }\n        stack.back().push_back({strArg, {}, {}});\n    };\n\n    auto close_out_params = [&]() {\n        if (nDepthInsideSensitive) {\n            if (!--nDepthInsideSensitive) {\n                // filter_begin_pos is set to chpos at the delimiter *after* the\n                // sensitive command name, which is always > 0 (at minimum the\n                // opening paren or space character follows the name).\n                assert(filter_begin_pos);\n                filter_ranges.emplace_back(filter_begin_pos, chpos);\n                filter_begin_pos = 0;\n            }\n        }\n        stack.pop_back();\n    };\n\n    std::string strCommandTerminated = strCommand;\n    if (strCommandTerminated.empty() || strCommandTerminated.back() != '\\n')\n        strCommandTerminated += '\\n';\n\n    for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos) {\n        char ch = strCommandTerminated[chpos];\n        switch (state) {\n        case STATE_COMMAND_EXECUTED_INNER:\n        case STATE_COMMAND_EXECUTED: {\n            bool breakParsing = true;\n            switch (ch) {\n            case '[':\n                curarg.clear();\n                state = STATE_COMMAND_EXECUTED_INNER;\n                break;\n            default:\n                if (state == STATE_COMMAND_EXECUTED_INNER) {\n                    if (ch != ']') {\n                        curarg += ch;\n                        break;\n                    }\n                    if (!curarg.empty()) last_result.queries.push_back(curarg);\n                    state = STATE_COMMAND_EXECUTED;\n                    break;\n                }\n                breakParsing = false;\n\n                close_out_params();\n\n                if (!stack.empty()) stack.back().push_back(last_result);\n                else plan->result = last_result;\n                curarg.clear();\n                state = STATE_EATING_SPACES;\n            }\n            if (breakParsing)\n                break;\n            [[fallthrough]];\n        }\n        case STATE_ARGUMENT:\n        case STATE_EATING_SPACES_IN_ARG:\n        case STATE_EATING_SPACES_IN_BRACKETS:\n        case STATE_EATING_SPACES:\n            switch (ch) {\n            case '\"':\n                state = STATE_DOUBLEQUOTED;\n                break;",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142Retained secret text is released without cleansingqml/secretinput.hstill_present
Assessment

The new-head header still declares `m_text` as a `const QString` and shows no cleansing destructor, so the retained UTF-16 buffer is not addressed by the supplied evidence.

new_source: qml/secretinput.h

[
  {
    "bounded": true,
    "end_line": 50,
    "evidence_id": "de6ac2273f4e4404a691ab783ef112f1",
    "finding_id": "finding:20",
    "kind": "new_source",
    "line": 4,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/secretinput.h",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "#ifndef BITCOIN_QML_SECRETINPUT_H\n#define BITCOIN_QML_SECRETINPUT_H\n#include <support/allocators/secure.h>\n#include <QString>\n#include <cstddef>\n#include <exception>\n#include <functional>\n#include <memory>\n#include <utility>\n\nnamespace walletopening { class Session; }\n\nnamespace secretinput {\nenum class Error { None, Unavailable, TransportBudget, Materialization };\nclass Failure final : public std::exception {\npublic:\n    explicit Failure(Error error) : m_error(error) {}\n    Error error() const noexcept { return m_error; }\n    const char* what() const noexcept override { return \"The secret input could not be materialized\"; }\nprivate:\n    Error m_error;\n};\n// Immutable Qt-native editor handoff. All UTF8 allocation/conversion, cleansing\n// and retirement run inside the original Native action, never on GUI.\nclass Input final {\npublic:\n    Input(QString text, size_t bytes);\n    size_t bytes() const { return m_bytes; }\n    SecureString materialize() const;\nprivate:\n    const QString m_text;\n    const size_t m_bytes;\n};\nusing Captured = std::shared_ptr<const Input>;\nstruct CaptureResult {\n    Captured input;\n    Error error{Error::None};\n    size_t bytes{0};\n    explicit operator bool() const { return bool(input) && error == Error::None; }\n};\n// O(1) metadata admission. result.bytes is the retained secret's accounted size.\nCaptureResult Capture(const std::function<std::shared_ptr<void>(std::function<void()>)>& hold, const QString& text);\nCaptureResult Capture(const std::shared_ptr<walletopening::Session>& opening, const QString& text);\nsize_t Bytes(const Captured& input);\nSecureString Materialize(const Captured& input);\n}\n#endif // BITCOIN_QML_SECRETINPUT_H",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142The raw-transaction fee cap overrides a raised wallet -maxtxfeeqml/walletsend.cppunclear
Assessment

The follow-up assessment was invalid: unknown follow-up evidence ID.

invalid_assessment

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142The helper commits claim enforcement that lands in later commitsqml/models/psbtfee.cppunclear
Assessment

This finding concerns commit-message claims and attribution across the commit series, while the supplied evidence is final-tree source and does not include amended commit messages or relevant per-commit metadata.

new_source: qml/models/psbtfee.cpp

[
  {
    "bounded": true,
    "end_line": 100,
    "evidence_id": "cb5fd565f725495f96d2bc6c546008df",
    "finding_id": "finding:18",
    "kind": "new_source",
    "line": 1,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/models/psbtfee.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "// Copyright (c) 2026 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <qml/models/psbtfee.h>\n\n#include <set>\n\nnamespace {\nbool AddAmount(CAmount& total, CAmount value)\n{\n    if (!MoneyRange(value) || value > MAX_MONEY - total) return false;\n    total += value;\n    return true;\n}\n}\n\npsbtfee::Analysis psbtfee::Analyze(const PartiallySignedTransaction& psbt, const Outputs& verified)\n{\n    Analysis result;\n    const auto tx = psbt.GetUnsignedTx();\n    if (!tx || tx->vin.empty() || tx->vout.empty()) return result;\n    result.commitment = tx->GetHash();\n    for (const auto& output : tx->vout) {\n        if (!AddAmount(result.output_total, output.nValue)) return result;\n    }\n    result.outputs_valid = true;\n    CAmount input_total{0};\n    bool missing{false};\n    std::set<COutPoint> seen;\n    for (const auto& input : psbt.inputs) {\n        const auto outpoint = input.GetOutPoint();\n        if (!seen.insert(outpoint).second) return result;\n        if (!input.witness_utxo.IsNull() && !MoneyRange(input.witness_utxo.nValue)) return result;\n        const auto trusted = verified.find(outpoint);\n        std::optional<CTxOut> prevout;\n        if (input.non_witness_utxo) {\n            if (input.non_witness_utxo->GetHash() != outpoint.hash || outpoint.n >= input.non_witness_utxo->vout.size()) return result;\n            prevout = input.non_witness_utxo->vout[outpoint.n];\n            if (trusted != verified.end() && trusted->second != *prevout) return result;\n        } else if (trusted != verified.end()) {\n            prevout = trusted->second;\n        } else {\n            missing = true;\n        }\n        if (prevout) {\n            if (!input.witness_utxo.IsNull() && input.witness_utxo != *prevout) return result;\n            if (!AddAmount(input_total, prevout->nValue)) return result;\n            result.verified.emplace(outpoint, *prevout);\n        }\n        result.prevouts.push_back(std::move(prevout));\n    }\n    if (missing) {\n        result.state = State::Missing;\n        return result;\n    }\n    if (input_total < result.output_total) return result;\n    result.state = State::Known;\n    result.amount = input_total - result.output_total;\n    return result;\n}\n\npsbtfee::Analysis psbtfee::Prepared(const CTransaction& transaction, CAmount fee)\n{\n    Analysis result;\n    if (!MoneyRange(fee)) return result;\n    const PartiallySignedTransaction psbt{CMutableTransaction{transaction}, /*version=*/2};\n    result.commitment = psbt.GetUnsignedTx()->GetHash();\n    result.amount = fee;\n    result.state = State::Known;\n    result.wallet_prepared = true;\n    return result;\n}\n\nbool psbtfee::MatchesReview(const PartiallySignedTransaction& psbt, const Analysis& proof, std::optional<CAmount> approved_fee)\n{\n    if (proof.state != State::Known || !approved_fee || proof.amount != approved_fee) return false;\n    const auto tx = psbt.GetUnsignedTx();\n    if (!tx || proof.commitment != tx->GetHash()) return false;\n    if (proof.wallet_prepared) {\n        // This aggregate fee came from Core's construction of these exact\n        // inputs/outputs, not from PSBT metadata. Metadata may only contradict\n        // that fact; it must never establish or replace it.\n        Outputs claims;\n        for (const auto& input : psbt.inputs) {\n            if (!input.witness_utxo.IsNull()) claims.emplace(input.GetOutPoint(), input.witness_utxo);\n        }\n        const auto claimed = Analyze(psbt, claims);\n        return claimed.state != State::Invalid && (!claimed.amount || claimed.amount == approved_fee);\n    }\n    return Analyze(psbt, proof.verified).amount == approved_fee;\n}\n\nvoid psbtfee::FillMissing(PartiallySignedTransaction& psbt, const Analysis& proof)\n{\n    for (auto& input : psbt.inputs) {\n        const auto found = proof.verified.find(input.GetOutPoint());\n        if (!input.non_witness_utxo && input.witness_utxo.IsNull() && found != proof.verified.end()) input.witness_utxo = found->second;\n    }\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142PSBT import automation bypasses the production import ownerqml/pages/wallet/SendCreate.qmlstill_present
Assessment

The shown new-head SendCreate path still routes `requestPsbtImport(path)` through `draftController.importPsbt(path)` and does not demonstrate injecting the selected file into the captured production import continuation. The requested test-path changes are also not evidenced.

new_source: qml/pages/wallet/SendCreate.qml

[
  {
    "bounded": true,
    "end_line": 186,
    "evidence_id": "c38a1afdd4a941818fd1986597d3e07b",
    "finding_id": "finding:17",
    "kind": "new_source",
    "line": 37,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/pages/wallet/SendCreate.qml",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "        && wallet.coinsListModel.lockedSatoshi > 0\n    readonly property string baseAvailableBalanceErrorText: qsTr(\"Amount plus fee exceeds available balance\")\n    readonly property string walletBalanceErrorText: qsTr(\"The wallet does not have enough balance for this transaction.\")\n    readonly property string availableBalanceErrorText: hasLockedCoins\n        ? qsTr(\"Amount plus fee exceeds available balance. Some of your coins are locked.\")\n        : baseAvailableBalanceErrorText\n    readonly property string selectedInputsBalanceErrorText: qsTr(\"Selected inputs do not cover the amount plus fee\")\n    readonly property string feeBalanceErrorText: wallet && wallet.sendAmountExhaustsBalance\n        ? (selectedInputsActive ? selectedInputsBalanceErrorText : availableBalanceErrorText)\n        : \"\"\n    readonly property string formErrorText: wallet && wallet.fees && !wallet.fees.estimatePending && wallet.fees.errorText.length > 0\n        ? wallet.fees.errorText : recipientValidationError.length > 0\n        ? recipientValidationError\n        : (wallet && wallet.coinsListModel && wallet.coinsListModel.selectionReconciliationRequired\n           ? qsTr(\"Some selected coins are no longer available. Choose Automatic inputs or update the selection.\")\n           : (feeBalanceErrorText.length > 0 ? feeBalanceErrorText : prepareTransactionErrorText))\n\n    signal viewTransactionInActivity(string txid)\n\n    // Prepares this page's draft for review and imports PSBT files. A result\n    // answers for the draft it was started for; hiding the page or another\n    // wallet drops it.\n    SendDraftController {\n        id: draftController\n        objectName: \"sendDraftController\"\n        draftInterface: root.wallet ? root.wallet.sendDraft : null\n        active: root.visible\n    }\n    function requestPsbtImport(path) {\n        if (!root.wallet || root.wallet.psbtActionBusy) return\n        draftController.importPsbt(path)\n    }\n    readonly property bool psbtImportDone: draftController.importState !== PsbtOperation.None\n        && draftController.importState !== PsbtOperation.Pending && draftController.importState !== PsbtOperation.Stale\n        && draftController.importState !== PsbtOperation.Cancelled\n    onPsbtImportDoneChanged: if (psbtImportDone) sendPage.handlePsbtImportResult(draftController.importResult)\n\n    function confirmTransactionReview() {\n        if (!sendPage.imports.pending) draftController.requestPreparation()\n    }\n\n    readonly property bool preparingReview: draftController.preparing\n\n    function prepareTransactionForReview() {\n        if (!root.wallet || !root.wallet.available || root.wallet.preparationBusy || sendPage.imports.pending) return\n        draftController.prepare()\n    }\n\n    readonly property bool preparationReady: draftController.preparationState === PreparationOperation.Ready\n    onPreparationReadyChanged: if (preparationReady) root.openTransactionReview()\n\n    function openTransactionReview() {\n        transactionReviewPopup.reviewWallet = root.wallet\n        transactionReviewPopup.importedReview = root.wallet.currentTransactionIsImportedPsbt === true\n        transactionReviewPopup.open()\n    }\n\n    function returnToSendForm() {\n        if (root.depth > 1) {\n            root.pop(null, StackView.Immediate)\n        }\n    }\n\n    function openPaymentRequestImport() {\n        root.returnToSendForm()\n        root.openWhileShown(sendPage.openPaymentRequestImport)\n    }\n\n    function acceptDesktopImport(mailbox: DesktopIntentModel): bool {\n        const imports = sendPage.imports\n        if (!mailbox || !imports.canAccept) return false\n        // Taking the inspection can change the selection; the import then\n        // belongs to no draft and is cancelled.\n        const context = imports.context\n        return imports.acceptImport(mailbox.takeInspection(imports), context)\n    }\n\n    function openPsbtFileImport() {\n        root.returnToSendForm()\n        root.openWhileShown(sendPage.openPsbtFileImport)\n    }\n\n    // The draft owner stamps captured user intent. Validation echoes and\n    // automatic Maximum observations do not create another user revision.\n    readonly property string draftRevision: root.wallet ? root.wallet.recipients.revision : \"\"\n    onDraftRevisionChanged: if (sendPage && reviewSweepAlert) root.draftChanged()\n\n    function draftChanged() {\n        sendPage.imports.draftChanged()\n    }\n\n    // Counts how often this page was hidden. A deferred open is dropped if\n    // the page was hidden in between, even if it is shown again by then.\n    property int hiddenCount: 0\n\n    function openWhileShown(open) {\n        const hiddenCount = root.hiddenCount\n        Qt.callLater(function() {\n            if (root.visible && hiddenCount === root.hiddenCount) open()\n        })\n    }\n\n    function clearPrepareTransactionError() {\n        draftController.dismissPreparationResult()\n    }\n\n    function resetSendForm() {\n        if (sendPage.imports.pending || !draftController.resetDraft()) return\n        root.clearPrepareTransactionError()\n        sendPage.expandedRecipient = 0\n        sendPage.imports.clearStatus()\n    }\n\n    function displayTransactionError(error) {\n        if (hasLockedCoins && !selectedInputsActive\n                && (error === baseAvailableBalanceErrorText || error === walletBalanceErrorText)) {\n            return availableBalanceErrorText\n        }\n        return error\n    }\n\n    function scheduleFeeEstimates() {\n        if (root.wallet) {\n            root.wallet.scheduleFeeEstimates()\n        }\n    }\n\n    function updateExpandedRecipient(index) {\n        sendPage.expandedRecipient = index\n    }\n\n    onVisibleChanged: if (!visible) root.hiddenCount++\n    onWalletChanged: {\n        if (transactionReviewPopup.opened) {\n            transactionReviewPopup.close()\n        }\n        root.pop()\n    }\n\n    Connections {\n        target: root.wallet ? root.wallet.recipients : null\n        function onListCleared() {\n            root.draftChanged()\n            root.clearPrepareTransactionError()\n            sendPage.expandedRecipient = 0\n            if (root.wallet) {\n                root.wallet.scheduleFeeEstimates()\n            }\n        }\n        function onCountChanged() {",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142Cancelled clipboard import objects accumulate during recipient editsqml/models/sendimportmodel.cppstill_present
Assessment

The new-head cancellation paths still disconnect and cancel operations without scheduling their deletion. Thus the cited QObject-retention issue remains in the shown code.

new_source: qml/models/sendimportmodel.cpp

[
  {
    "bounded": true,
    "end_line": 248,
    "evidence_id": "ad5dcfcf73a04140892ca13f8ae0801b",
    "finding_id": "finding:16",
    "kind": "new_source",
    "line": 205,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/models/sendimportmodel.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "}\n\nvoid SendImportModel::cancelImport()\n{\n    m_presented_result.clear();\n    if (const auto operation = std::exchange(m_operation, nullptr)) {\n        disconnect(operation, nullptr, this, nullptr);\n        operation->cancel();\n    }\n    Q_EMIT changed();\n}\n\nvoid SendImportModel::cancelAll()\n{\n    cancelImport();\n    if (const auto check = std::exchange(m_clipboard_check, nullptr)) {\n        disconnect(check, nullptr, this, nullptr);\n        check->cancel();\n    }\n    Q_EMIT changed();\n}\n\nvoid SendImportModel::checkClipboard()\n{\n    if (const auto check = std::exchange(m_clipboard_check, nullptr)) {\n        disconnect(check, nullptr, this, nullptr);\n        check->cancel();\n    }\n    if (m_active && m_target && m_target->available() && !m_target->importPending() && !m_clipboard_text.trimmed().isEmpty()) {\n        m_offered_text = m_clipboard_text;\n        m_clipboard_check = m_target->importText(m_offered_text, this);\n        if (m_clipboard_check) connect(m_clipboard_check, &ImportOperation::changed, this, &SendImportModel::changed);\n    }\n    Q_EMIT changed();\n}\n\nvoid SendImportModel::presentReview()\n{\n    if (!m_operation || !m_operation->reviewOpened() || !m_target || !m_target->available()) return;\n    const auto token = m_operation->resultToken();\n    if (token.isEmpty() || token == m_presented_result || m_target->importedReviewToken() != token) return;\n    m_presented_result = token;\n    Q_EMIT reviewReady();\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142The Activity hold timer undoes its own final scroll clampqml/pages/wallet/ActivityListPage.qmlstill_present
Assessment

The timer still calls `restorePosition(true)` before clearing `heldContentY`, leaving the same re-entry condition described in the finding. No clamp/re-entry change is shown.

new_source: qml/pages/wallet/ActivityListPage.qml

[
  {
    "bounded": true,
    "end_line": 502,
    "evidence_id": "ebf664c1a85a4170bcc79f9bf5498863",
    "finding_id": "finding:15",
    "kind": "new_source",
    "line": 353,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/pages/wallet/ActivityListPage.qml",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "                }\n                // A confirmation re-groups the list: rows move out of Pending into\n                // their dated groups. Qt keeps each visible row on screen as it moves,\n                // so the view follows the row up the list and jumps. The list stays\n                // where the user left it instead, at the top or further down. Only the\n                // position is held while the move is applied; the rows still move.\n                // The user always wins: a drag, a flick, the scroll bar or the wheel\n                // ends the hold.\n                property real heldContentY: NaN\n                readonly property bool userScrolling: moving || dragging || (ScrollBar.vertical && ScrollBar.vertical.pressed)\n                function holdPosition() {\n                    if (isNaN(heldContentY) && !userScrolling) heldContentY = contentY\n                    if (!isNaN(heldContentY)) holdPositionTimer.restart()\n                }\n                // While the list lays out the moved rows its content height is only an\n                // estimate, and Qt clamps the position to it and does not come back.\n                // So hold the exact position meanwhile and clamp only once settled.\n                function restorePosition(settled) {\n                    const held = heldContentY\n                    if (isNaN(held)) return\n                    if (userScrolling) { heldContentY = NaN; return }\n                    const highest = Math.max(originY, originY + contentHeight - height)\n                    const target = settled === true ? Math.max(originY, Math.min(held, highest)) : held\n                    if (contentY !== target) contentY = target\n                }\n                onContentYChanged: restorePosition(false)\n                onUserScrollingChanged: if (userScrolling) heldContentY = NaN\n                Timer {\n                    id: holdPositionTimer\n                    interval: 400\n                    onTriggered: { listView.restorePosition(true); listView.heldContentY = NaN }\n                }\n                Connections {\n                    target: activityFilterProxy\n                    function onRowsAboutToBeMoved() { listView.holdPosition() }\n                    function onModelAboutToBeReset() { listView.holdPosition() }\n                    function onLayoutAboutToBeChanged() { listView.holdPosition() }\n                    function onRowsMoved() { listView.restorePosition(false); listView.holdPosition() }\n                    function onModelReset() { listView.restorePosition(false); listView.holdPosition() }\n                    function onLayoutChanged() { listView.restorePosition(false); listView.holdPosition() }\n                    function onDataChanged() { if (!isNaN(listView.heldContentY)) listView.holdPosition() }\n                }\n                Timer {\n                    id: focusScrollTimer\n                    interval: 0\n                    onTriggered: listView.ensureFocusedItemVisible()\n                }\n                Connections {\n                    target: root.Window.window\n                    function onActiveFocusItemChanged() { focusScrollTimer.restart() }\n                }\n                anchors.fill: parent\n                anchors.topMargin: activityRefreshError.visible ? activityRefreshError.height + 8 : 0\n                clip: true\n                model: root.visible ? activityFilterProxy : null\n                reuseItems: false\n                boundsBehavior: Flickable.StopAtBounds\n                // Nothing on this page uses the current item. Left at its default it\n                // is the first row and is pushed down by every row inserted above\n                // it; when a confirmation re-groups the list, the view then jumps\n                // to that row instead of staying where the user left it.\n                currentIndex: -1\n                highlightFollowsCurrentItem: false\n                ScrollBar.vertical: ScrollBar {}\n                // Constant: rewriting it while the hidden page's model releases\n                // its rows reads a row without its attached object and crashes.\n                section.property: \"sectionLabel\"\n                section.criteria: ViewSection.FullString\n                section.delegate: Item {\n                    id: sectionHeader\n                    required property string section\n                    readonly property bool isPending: section === qsTranslate(\"ActivityFilterProxyModel\", \"Pending\")\n                    width: listView.width\n                    height: 56\n                    RowLayout {\n                        anchors.left: parent.left\n                        anchors.right: parent.right\n                        anchors.leftMargin: root.activitySideInset + Theme.space.xs\n                        anchors.rightMargin: root.activitySideInset + Theme.space.xs\n                        anchors.bottom: parent.bottom\n                        anchors.bottomMargin: 12\n                        spacing: 12\n                        CoreText {\n                            objectName: \"activitySectionTitle\"\n                            Layout.fillWidth: true\n                            text: sectionHeader.section\n                            textStyle: Theme.text.subheading\n                            horizontalAlignment: Text.AlignLeft\n                        }\n                        BitcoinAmountDisplayLabel {\n                            objectName: sectionHeader.isPending ? \"activityPendingBalance\" : \"\"\n                            hidesAmount: true\n                            visible: sectionHeader.isPending && activityFilterProxy.pendingBalanceSat !== 0\n                            text: visible ? activityFilterProxy.pendingBalance : \"\"\n                            textStyle: Theme.text.amountDescription\n                            color: !visible ? Theme.color.neutral7 : activityFilterProxy.pendingBalanceSat > 0 ? Theme.color.txIncoming\n                                : activityFilterProxy.pendingBalanceSat < 0 ? Theme.color.neutral9 : Theme.color.neutral7\n                            horizontalAlignment: Text.AlignRight\n                        }\n                    }\n                }\n                delegate: Item {\n                    id: activityDelegate\n                    required property var model\n                    required property int index\n                    width: listView.width\n                    height: activityRow.implicitHeight + (activityPreviewNotice.visible ? activityPreviewNotice.implicitHeight + Theme.space.m : 0)\n                    CoreText {\n                        id: activityPreviewNotice\n                        anchors.top: activityRow.bottom\n                        anchors.topMargin: Theme.space.xs\n                        x: root.activitySideInset\n                        width: root.activityContentWidth\n                        visible: activityDelegate.model.presentationLimited === true\n                        text: qsTr(\"A preview is shown. Open the transaction for complete details.\")\n                        textStyle: Theme.text.description\n                        color: Theme.color.neutral7\n                    }\n                    ActivityRow {\n                        id: activityRow\n                        isCompact: activitySettings.activityDisplayDensity === \"compact\"\n                        x: root.activitySideInset\n                        width: root.activityContentWidth\n                        activityId: activityDelegate.model.activityId\n                        txid: activityDelegate.model.txid\n                        requestId: activityDelegate.model.requestId\n                        label: activityDelegate.model.label\n                        address: activityDelegate.model.address\n                        amount: activityDelegate.model.amount\n                        netAmountSat: activityDelegate.model.netAmountSat\n                        dateTimeLabel: activityDelegate.model.dateTimeLabel\n                        activityType: activityDelegate.model.activityType\n                        status: activityDelegate.model.status\n                        depth: activityDelegate.model.depth\n                        blocksToMaturity: activityDelegate.model.blocksToMaturity\n                        statusKnown: activityDelegate.model.statusKnown\n                        isInactive: activityDelegate.model.isInactive\n                        isPendingRequest: activityDelegate.model.isPendingRequest\n                        replacedByTxid: activityDelegate.model.replacedByTxid\n                        hasPaymentRequest: activityDelegate.model.hasPaymentRequest\n                        actions: activityDelegate.model.actions\n                        firstInSection: activityDelegate.ListView.section !== activityDelegate.ListView.previousSection\n                        lastInSection: activityDelegate.ListView.section !== activityDelegate.ListView.nextSection\n                        onContextMenuRequested: function(x, y) {\n                            const menu = activityRow.isPendingRequest ? activityRequestMenu : activityRowMenu\n                            const point = activityRow.mapToItem(menu.parent, x, y)\n                            if (activityRow.isPendingRequest) {\n                                activityRequestMenu.requestId = activityRow.requestId\n                            } else {\n                                // The proxy keeps a delayed raw copy bound to this row.",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142Payment and PSBT import errors are hard-coded Englishqml/paymentimport.cppstill_present
Assessment

The new-head excerpt continues to construct reader and analysis errors using `QStringLiteral`, including unsupported-source and malformed-PSBT errors. The shown changes address other import behavior, not translation.

new_source: qml/paymentimport.cpp

[
  {
    "bounded": true,
    "end_line": 216,
    "evidence_id": "cf935add030b406588c2127171a7ef28",
    "finding_id": "finding:14",
    "kind": "new_source",
    "line": 67,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/paymentimport.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "            return Invalid(QStringLiteral(\"The import source is too large or could not be read.\"));\n    } else {\n        if (value.size() > MAX_TEXT) return Invalid(QStringLiteral(\"The import source is too large.\"));\n        bytes = value.toUtf8();\n    }\n    Inspection result;\n    result.field = input.field;\n    result.source_identity = QString::fromLatin1(QCryptographicHash::hash(bytes, QCryptographicHash::Sha256).toHex()) + QLatin1Char(':') +\n        QString::fromLatin1(QCryptographicHash::hash(identity_path.toUtf8(), QCryptographicHash::Sha256).toHex());\n    const auto text = QString::fromUtf8(bytes).trimmed();\n    if (text.startsWith(QStringLiteral(\"bitcoin:\"), Qt::CaseInsensitive)) {\n        const auto payment = BitcoinUri::Parse(text);\n        if (!payment.success) return Invalid(payment.error);\n        if (payment.address.size() > 1024 || payment.label.size() > senddraft::Limits::note ||\n            payment.message.size() > senddraft::Limits::message) return Invalid(QStringLiteral(\"The payment request metadata is too large.\"));\n        result.kind = Kind::Payment;\n        result.payment.address = payment.address;\n        result.payment.label = payment.label;\n        result.payment.message = payment.message;\n        if (payment.has_amount) result.payment.amount = payment.amount_sats;\n        result.payment_identity = PaymentIdentity(result.payment);\n        // Public URI fields never manufacture a user-authored private note.\n        return result;\n    }\n    const auto raw = DecodeRawPSBT(std::as_bytes(std::span{bytes.constData(), static_cast<size_t>(bytes.size())}));\n    auto document = raw ? std::optional<PartiallySignedTransaction>{*raw} : std::nullopt;\n    if (!document) {\n        const auto decoded = DecodeBase64PSBT(text.toStdString());\n        if (decoded) document = *decoded;\n    }\n    if (!document) return Invalid(QStringLiteral(\"The source is not a supported payment request or PSBT.\"));\n    const auto transaction = document->GetUnsignedTx();\n    if (!transaction || transaction->vin.empty() || transaction->vout.empty() ||\n        document->inputs.size() != transaction->vin.size() || document->outputs.size() != transaction->vout.size())\n        return Invalid(QStringLiteral(\"The PSBT is malformed.\"));\n    auto parsed = std::make_shared<psbtwork::Snapshot>();\n    parsed->document = std::make_shared<const PartiallySignedTransaction>(std::move(*document));\n    result.kind = Kind::Psbt;\n    result.psbt = std::move(parsed);\n    return result;\n}\n\nInspection AnalyzeSource(const Inspection& source, const psbtfee::Lookup& lookup)\n{\n    if (source.kind != Kind::Psbt || !source.psbt || !source.psbt->document) return Invalid(QStringLiteral(\"No PSBT is available for inspection.\"));\n    psbtwork::Request request;\n    request.kind = psbtwork::Kind::Inspect;\n    request.document = source.psbt->document;\n    psbtwork::Context context; context.lookup = lookup;\n    const auto analyzed = psbtwork::Execute(nullptr, std::move(request), context);\n    if (!analyzed.snapshot) return Invalid(analyzed.error.isEmpty() ? QStringLiteral(\"The PSBT could not be inspected.\") : analyzed.error);\n    auto result = source;\n    result.psbt = analyzed.snapshot;\n    return result;\n}\n\nstruct Owner::Reply {\n    std::optional<Target> target;\n    std::optional<ChildReply> child;\n    std::exception_ptr error;\n};\nstruct Owner::Delivery {\n    struct Cell {\n        std::mutex mutex;\n        bool ready{false};\n        Reply reply;\n    };\n    std::shared_ptr<Cell> cell;\n    std::shared_ptr<void> outcome;\n    ReplyKind kind;\n    std::optional<Child> child;\n    uint64_t identity{0}, source{0}, target{0};\n    void complete(Reply value)\n    {\n        std::shared_ptr<void> release;\n        {\n            std::lock_guard lock{cell->mutex};\n            if (!cell->ready) {\n                cell->reply = std::move(value);\n                cell->ready = true;\n                release = std::move(outcome);\n            }\n        }\n        release.reset();\n    }\n};\nstruct Owner::State {\n    Flow flow;\n    std::shared_ptr<const Input> input;\n    std::shared_ptr<const Inspection> inspection;\n    std::shared_ptr<const TargetPort> target;\n    std::shared_ptr<const ChildReply> result;\n    std::map<uint64_t, std::shared_ptr<Delivery>> deliveries;\n    uint64_t sequence{0}, target_sequence{0}, delivery_sequence{0}, query_delivery{0};\n    size_t native_jobs{0};\n    QString error;\n    bool closing{false}, retired{false}, wake_pending{false}, use_requested{false};\n    std::chrono::steady_clock::time_point retry_at{};\n};\nOwner::Owner(uint64_t identity, Services services, Notify notify, Retired retired, std::shared_ptr<State> state)\n    : m_identity(identity), m_services(std::move(services)),\n      m_outcomes(std::make_shared<execution::ValueCleanupQueue>(m_services.outcomes)), m_notify(std::move(notify)),\n      m_retired(std::move(retired)), m_state(std::move(state)) {}\n\nstd::shared_ptr<Owner> Owner::Create(uint64_t identity, Services services, Notify notify, Retired retired)\n{\n    if (!identity || !services.reads || !services.outcomes) return {};\n    if (!services.read) services.read = ReadSource;\n    if (!services.analyze) services.analyze = [](const Inspection& source) { return AnalyzeSource(source); };\n    if (!services.now) services.now = std::chrono::steady_clock::now;\n    auto owner = std::shared_ptr<Owner>{new Owner(identity, std::move(services), std::move(notify),\n        std::move(retired), std::make_shared<State>())};\n    auto closing = std::make_shared<std::shared_ptr<Owner>>();\n    auto reservation = owner->m_outcomes->hold([closing] {\n        if (*closing) (*closing)->closeOnQueue();\n    });\n    if (!reservation) return owner;\n    owner->m_post_close = [closing, reservation = std::move(reservation)](auto self) mutable {\n        *closing = std::move(self);\n        reservation.reset();\n    };\n    return owner;\n}\n\nexecution::SubmitResult Owner::submit(std::function<void()> decision)\n{\n    auto run = [self = shared_from_this(), decision = std::move(decision)] {\n        decision(); self->publish();\n    };\n    const bool accepted = m_services.outcomes->post(std::move(run));\n    return {{}, accepted ? execution::Rejection::None : execution::Rejection::Transport};\n}\n\nvoid Owner::publish()\n{\n    auto& state = *m_state;\n    Snapshot snapshot;\n    snapshot.sequence = ++state.sequence; snapshot.owner = m_identity; snapshot.source = state.flow.source();\n    snapshot.phase = state.flow.phase(); snapshot.kind = state.flow.kind(); snapshot.error_code = state.flow.error();\n    snapshot.error = state.error; snapshot.target = state.flow.target(); snapshot.prompt = state.flow.prompt();\n    snapshot.result = state.flow.result(); snapshot.inspection = state.inspection; snapshot.child_result = state.result;\n    snapshot.pending = state.flow.pending() || state.native_jobs || !state.deliveries.empty();\n    if (snapshot.phase == Phase::Closed && snapshot.pending) snapshot.phase = Phase::Closing;\n    snapshot.can_apply = state.flow.canApply(); snapshot.can_review = state.flow.canReview();\n    snapshot.can_export = state.flow.canExport(); snapshot.can_reconcile = state.flow.canReconcile();\n    try { if (m_notify) m_notify(std::move(snapshot)); } catch (...) {}\n    if (state.flow.phase() == Phase::Closed && !state.native_jobs && state.deliveries.empty() && !state.retired) {\n        state.retired = true;\n        state.target.reset();\n        state.result.reset();",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142The same pasted passphrase can create a wallet but fail to unlock itqml/controls/PasswordTextField.qmlstill_present
Assessment

The new-head field still silently removes CR/LF from new-passphrase input through `dropLineEndings()`. It does not reject the input visibly or preserve the pasted value for correction.

new_source: qml/controls/PasswordTextField.qml

[
  {
    "bounded": true,
    "end_line": 58,
    "evidence_id": "1322e2e1f6ac413b826d620108037c15",
    "finding_id": "finding:13",
    "kind": "new_source",
    "line": 1,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/controls/PasswordTextField.qml",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "// Copyright (c) 2026 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\nimport QtQuick 2.15\n\nLabeledTextField {\n    id: root\n\n    property bool passwordVisible: false\n    property string visibilityToggleObjectName: root.objectName.length > 0\n        ? root.objectName + \"VisibilityToggle\"\n        : \"\"\n\n    // For a new passphrase only. A line ending cannot be typed into this\n    // field, so one that arrives by paste is dropped instead of becoming a\n    // character the user cannot see or type again. Fields that unlock an\n    // existing wallet leave this off: a wallet encrypted with a pasted line\n    // ending must still open with exactly that text.\n    property bool dropsLineEndings: false\n\n    function dropLineEndings() {\n        const text = root.field.text\n        if (!root.dropsLineEndings || !/[\\r\\n]/.test(text)) return\n        const caret = text.slice(0, root.field.cursorPosition).replace(/[\\r\\n]/g, \"\").length\n        root.field.text = text.replace(/[\\r\\n]/g, \"\")\n        root.field.cursorPosition = caret\n    }\n\n    Connections {\n        target: root.field\n        function onTextChanged() { root.dropLineEndings() }\n    }\n    onDropsLineEndingsChanged: dropLineEndings()\n\n    echoMode: passwordVisible ? TextInput.Normal : TextInput.Password\n    // Qt never exposes a name for a password field, so the label also goes\n    // into the description, which VoiceOver still reads.\n    accessibleDescription: [label, errorText.length > 0 ? errorText : supportingText]\n        .filter(function(part) { return part.length > 0 }).join(\". \")\n    inputMethodHints: Qt.ImhSensitiveData | Qt.ImhNoPredictiveText\n\n    trailingItem: IconButton {\n        id: visibilityToggle\n        objectName: root.visibilityToggleObjectName\n        size: 30\n        iconSize: 22\n        iconSource: root.passwordVisible ? \"qrc:/icons/hidden\" : \"qrc:/icons/visible\"\n        iconColor: Theme.color.neutral7\n        activeColor: Theme.color.neutral9\n        enabled: root.enabled\n        // Clicking keeps focus in the field; Tab still reaches the toggle.\n        focusPolicy: Qt.TabFocus\n        accessibleName: root.passwordVisible ? qsTr(\"Hide password\") : qsTr(\"Show password\")\n        background: null\n        onClicked: root.passwordVisible = !root.passwordVisible\n    }\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142Sign-only enables broadcast readiness without a policy assessmentqml/models/walletsendhandle.cppstill_present
Assessment

The shown sign-only success path still enables broadcast based on node presence and `!result->partial`, without a policy assessment. The change shown only selects a wallet-specific policy for the operation; it does not assess readiness before enabling broadcast.

new_source: qml/models/walletsendhandle.cpp

[
  {
    "bounded": true,
    "end_line": 577,
    "evidence_id": "46fa50046964498caac5a2f20ff84bd3",
    "finding_id": "finding:12",
    "kind": "new_source",
    "line": 483,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/models/walletsendhandle.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "    m_coins_list_model->setManualInputSelection(false);\n    m_coins_list_model->update();\n    if (!self) return;\n    Q_EMIT sentDraftCleared();\n}\n\nvoid WalletModel::finishSendWork(const std::shared_ptr<walletsend::SendTask>& work, const QPointer<TransactionReviewModel>& review,\n                                    bool sign_only, const QPointer<WalletSendHandle> &operation)\n{\n    if (!observationsAllowed() || m_closed || !work) return;\n    const auto result = work->result();\n    if (!result) return;\n    const QPointer<WalletModel> self{this};\n    if (work == m_send_operation) setSendRunning(false);\n    if (!self) return;\n    const auto [outcome, message] = DescribeSendResult(*result, sign_only);\n    const auto tell = [&](bool review_current) {\n        if (operation) operation->workFinished(*result, review_current);\n    };\n    const bool review_current = available() && review && review == m_current_transaction;\n    if (sign_only && result->document && !result->quarantined_document && review_current) {\n        // A sign-only result may contain new valid partial signatures even\n        // when the wallet reported a terminal signing error. Preserve that\n        // captured document, while allowing broadcast only after a clean,\n        // verified complete result.\n        invalidateImportReview();\n        review->setPsbt(result->document);\n        review->setAssessedPsbt(result->document);\n        if (result->error == walletsend::Error::None && !result->relock_failed) {\n            if (result->signed_transaction) { review->setWtx(result->signed_transaction); if (!self) return; }\n            review->setCanBroadcast(m_node && !result->partial);\n            setTransactionStatus(message);\n            Q_EMIT currentTransactionChanged();\n            if (!self) return;\n            tell(true);\n            return;\n        }\n    }\n    if (result->committed && result->notes_requested) {\n        m_sent_labels_work = work;\n        m_sent_labels_operation = result->notes;\n        m_sent_labels_txid = QString::fromStdString(result->committed->GetHash().GetHex());\n        m_sent_labels_pending = bool(result->notes);\n        m_sent_labels_error = result->notes ? QString{}\n            : result->record != walletsend::Record::Recorded\n                ? tr(\"The wallet transaction record could not be confirmed, so its outgoing notes were not saved.\")\n            : result->notes_rejection == execution::Rejection::Transport\n                ? tr(\"The transaction was committed, but its outgoing note results could not be confirmed.\")\n                : tr(\"The transaction was saved to the wallet, but its outgoing notes could not be saved.\");\n        publishSentRecipientLabels();\n        if (!self) return;\n    }\n    m_opening->refreshMetadata();\n    if (!self) return;\n    // A consumed effect belongs to its original review. A successor gets no\n    // old success, password prompt, mutation or transaction error.\n    if (!available() || !review || review != m_current_transaction) {\n        tell(false);\n        return;\n    }\n    if (result->committed) {\n        review->setCanSend(false); review->setCanBroadcast(false);\n        review->setWtx(result->committed);\n        if (!self || !review || review != m_current_transaction) return;\n        review->setPsbt({}); m_psbt_document_lease.reset(); review->setRequiresRecheck(false);\n        review->setSource(CurrentTransactionSource::None);\n        review->setReviewMessage({}); clearTransactionStatus();\n        if (!self || !review || review != m_current_transaction) return;\n        clearSelectedCoins();\n        if (!self) return;\n        // The sent payment leaves the form, even when its page is hidden or\n        // gone. A draft changed since the review (an import) is newer and stays.\n        if (!sign_only && m_send_recipients->revision() == m_send_draft_revision) clearSentDraft();\n        if (!self) return;\n    } else {\n        if (result->quarantined_document) {\n            review->setCanSend(false);\n            review->setCanBroadcast(false);\n        }\n        if (outcome == SendOperation::State::Uncertain) review->setCanSend(false);\n        setTransactionStatus(message, outcome == SendOperation::State::NeedsUnlock);\n        if (!self) return;\n        if (sign_only && (result->document || result->quarantined_document)) {\n            Q_EMIT currentTransactionChanged();\n            if (!self) return;\n            Q_EMIT signerApprovalChanged();\n            if (!self) return;\n        }\n    }\n    if (result->committed || outcome == SendOperation::State::Uncertain) {\n        Q_EMIT currentTransactionChanged();\n        if (!self) return;\n    }\n    tell(true);\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142A refused Receive type stays hidden after descriptor importqml/walletopening.cppstill_present
Assessment

The new-head excerpt retains the same negative-cache insertion and lookup behavior; it shows no clearing or re-probing of unavailable receive types on capability changes. The excerpt does not include the capability-change callback, so whether it was separately changed is not established by this evidence.

new_source: qml/walletopening.cpp

[
  {
    "bounded": true,
    "end_line": 659,
    "evidence_id": "81c1152b4f0d43c2bef8228d60c20bc0",
    "finding_id": "finding:11",
    "kind": "new_source",
    "line": 510,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/walletopening.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "        if (transactions) m_pending.transaction_revision = m_transaction_revision;\n        m_retry_after = m_clock() + std::chrono::seconds{std::min(30U, 1U << m_refresh_failures)};\n        m_refresh_failures = std::min(5U, m_refresh_failures + 1);\n    }\n    Update update; update.failed = true; publish(std::move(update));\n}\n\nOutputType Session::preferredReceiveType(interfaces::Wallet& wallet) const\n{\n    const auto saved = m_preferences.read ? m_preferences.read(wallet.getWalletName()) : std::string{};\n    const auto parsed = ParseOutputType(saved);\n    // A saved choice wins, then an explicit -addresstype, then Taproot, the\n    // app's own default (#932, #1137). Core's implicit default is not used.\n    const OutputType preferred = parsed ? *parsed\n        : gArgs.IsArgSet(\"-addresstype\") ? wallet.getDefaultAddressType()\n        : wallet.taprootEnabled() ? OutputType::BECH32M : wallet.getDefaultAddressType();\n    std::lock_guard lock{m_receive_types_mutex};\n    if (!m_unavailable_receive_types.contains(preferred)) return preferred;\n    // #1088: fall back in the order Receive lists types. Without a Core\n    // capability query, a type is only known unavailable once it has failed.\n    for (const OutputType type : {OutputType::BECH32M, OutputType::BECH32, OutputType::P2SH_SEGWIT, OutputType::LEGACY}) {\n        if (type == OutputType::BECH32M && !wallet.taprootEnabled()) continue;\n        if (!m_unavailable_receive_types.contains(type)) return type;\n    }\n    return preferred;\n}\n\nvoid Session::markReceiveTypeUnavailable(OutputType type)\n{\n    std::lock_guard lock{m_receive_types_mutex};\n    m_unavailable_receive_types.insert(type);\n}\n\nstd::vector<std::string> Session::unavailableReceiveTypes() const\n{\n    std::lock_guard lock{m_receive_types_mutex};\n    std::vector<std::string> ids;\n    ids.reserve(m_unavailable_receive_types.size());\n    for (const OutputType type : m_unavailable_receive_types) ids.push_back(FormatOutputType(type));\n    return ids;\n}\n\nexecution::SubmitResult Session::setReceivePreference(std::string type, std::shared_ptr<const Action> original, std::function<void(bool)> done)\n{\n    if (type != \"bech32m\" && type != \"bech32\" && type != \"p2sh-segwit\" && type != \"legacy\") return {{}, execution::Rejection::Invalid};\n    if (original && original->identity() != identity()) return {{}, execution::Rejection::Invalid};\n    const auto revision = ++m_preference_revision;\n    const auto self = shared_from_this();\n    const auto work = [self, type](interfaces::Wallet& wallet) {\n        const bool supported = type != \"bech32m\" || wallet.taprootEnabled();\n        const bool persisted = supported && self->m_preferences.write && self->m_preferences.write(wallet.getWalletName(), type);\n        auto metadata = ReadMetadata(wallet, self->m_preferences, self->unavailableReceiveTypes());\n        const bool saved = persisted && metadata.receive_preference == type;\n        return std::pair{std::move(metadata), saved};\n    };\n    const auto complete = [self, revision, done](std::pair<Metadata, bool> result) {\n        const bool saved = result.second;\n        Update update; update.metadata = std::move(result.first); update.preference_saved = result.second; update.preference_revision = revision;\n        update.phase = self->m_state.phase(); update.question = self->m_state.question();\n        self->publish(std::move(update));\n        try { if (done) done(saved); } catch (...) { }\n    };\n    const auto failed = [self, revision, done](std::exception_ptr) {\n        Update update; update.preference_saved = false; update.preference_revision = revision;\n        update.phase = self->m_state.phase(); update.question = self->m_state.question();\n        self->publish(std::move(update));\n        try { if (done) done(false); } catch (...) { }\n    };\n    const auto submitted = original ? perform(original, work, complete, failed)\n                                    : read(work, complete, failed, execution::WorkClass::Action);\n    if (!submitted) {\n        Update update; update.preference_saved = false; update.preference_revision = revision;\n        publish(std::move(update));\n    }\n    return submitted;\n}\n\nvoid Session::refreshed(Metadata metadata, Update events)\n{\n    Transactions consumer;\n    { std::lock_guard lock{m_mutex}; m_refresh_pending = false; m_refresh_failures = 0; m_retry_after = {}; consumer = m_transactions_consumer; }\n    if (!available()) return;\n    if (consumer && (!events.transactions.empty() || events.rescan)) consumer(events.transaction_revision, events.transactions, events.rescan);\n    events.metadata = std::move(metadata);\n    events.phase = m_state.phase();\n    events.question = m_state.question();\n    publish(std::move(events));\n    scheduleRefresh();\n}\n\nvoid Session::publishState()\n{\n    Update update;\n    update.phase = m_state.phase();\n    update.question = m_state.question();\n    publish(std::move(update));\n}\n\nvoid Session::publish(Update update)\n{\n    bool notify;\n    {\n        std::lock_guard lock{m_mutex};\n        if (m_latest) {\n            update.transaction_revision = std::max(update.transaction_revision, m_latest->transaction_revision);\n            if (!update.metadata) update.metadata = std::move(m_latest->metadata);\n            if (!update.preference_saved) {\n                update.preference_saved = m_latest->preference_saved;\n                update.preference_revision = m_latest->preference_revision;\n            }\n            for (const auto& [id, change] : m_latest->transactions) {\n                if (update.transactions.size() < 256) update.transactions.try_emplace(id, change);\n                else update.rescan = true;\n            }\n            update.addresses |= m_latest->addresses;\n            update.status |= m_latest->status;\n            update.rescan |= m_latest->rescan;\n            update.unloaded |= m_latest->unloaded;\n            update.failed |= m_latest->failed;\n        }\n        if (m_closed->load()) {\n            update.phase = m_drained.load() ? Phase::Closed : Phase::Closing;\n            update.question.reset();\n        }\n        m_latest = std::move(update);\n        notify = !std::exchange(m_notice_pending, true);\n    }\n    if (notify) m_notify();\n}\n\nstd::optional<Update> Session::take()\n{\n    std::lock_guard lock{m_mutex};\n    m_notice_pending = false;\n    return std::exchange(m_latest, {});\n}\n\nvoid Session::acknowledgeTransactions()\n{\n    std::lock_guard lock{m_mutex};\n    if (!m_refresh_pending && m_pending.transactions.empty() && !m_pending.rescan &&\n        (!m_latest || (m_latest->transactions.empty() && !m_latest->rescan))) m_transactions_pending = false;\n}\nSession::Preferences ChainPreferences(interfaces::Chain& chain)\n{\n    return {\n        [&chain](const std::string& name) {\n            const auto values = chain.getRwSetting(\"qml_receive_address_types\");\n            const auto& value = values[name];\n            return value.isStr() ? value.get_str() : std::string{};",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142The additive cluster check can veto an accepted replacementqml/psbtpolicy.cppaddressed
Assessment

The policy now allows exact `testmempoolaccept` admission to supersede the additive chain-limit check, while still blocking when admission is not Allowed. This directly removes the reported veto for an accepted replacement.

path_diff: qml/psbtpolicy.cpp; new_source: qml/psbtpolicy.cpp

[
  {
    "evidence_id": "f61dbb127e304d55b089355229ac591d",
    "finding_id": "finding:10",
    "kind": "path_diff",
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/psbtpolicy.cpp",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "diff --git a/qml/psbtpolicy.cpp b/qml/psbtpolicy.cpp\nindex dac47edbc0..3cd08b0509 100644\n--- a/qml/psbtpolicy.cpp\n+++ b/qml/psbtpolicy.cpp\n@@ -25,15 +25,16 @@\n namespace {\n QString Tr(const char* text) { return QCoreApplication::translate(\"PsbtQmlModel\", text); }\n \n-void ReadAdmission(interfaces::Node& node, const CTransaction& transaction, psbtpolicy::Facts& facts)\n+void ReadAdmission(interfaces::Node& node, const CTransaction& transaction, psbtpolicy::Facts& facts, bool enforce_raw_fee_cap)\n {\n     try {\n         UniValue raw_transactions{UniValue::VARR};\n         raw_transactions.push_back(EncodeHexTx(transaction));\n         UniValue parameters{UniValue::VARR};\n         parameters.push_back(std::move(raw_transactions));\n-        // The same fee-rate cap that submission passes to broadcastTransaction.\n-        parameters.push_back(ValueFromAmount(psbtpolicy::MAX_FEE_RATE.GetFeePerK()));\n+        // Raw PSBT broadcasts pass MAX_FEE_RATE to broadcastTransaction; wallet\n+        // sends and fee bumps already checked the wallet's own -maxtxfee limit.\n+        parameters.push_back(enforce_raw_fee_cap ? ValueFromAmount(psbtpolicy::MAX_FEE_RATE.GetFeePerK()) : UniValue{0});\n         const UniValue response = node.executeRpc(\"testmempoolaccept\", parameters, \"\");\n         if (!response.isArray() || response.size() != 1) return;\n         const UniValue& result = response[0];\n@@ -99,12 +100,12 @@ void ClearAdmissionFacts(psbtpolicy::Facts& facts)\n }\n } // namespace\n \n-psbtpolicy::Read psbtpolicy::ReadNode(interfaces::Node* node, interfaces::Chain* chain)\n+psbtpolicy::Read psbtpolicy::ReadNode(interfaces::Node* node, interfaces::Chain* chain, bool enforce_raw_fee_cap)\n {\n-    return [node, chain](CTransactionRef transaction, CAmount fee) {\n+    return [node, chain, enforce_raw_fee_cap](CTransactionRef transaction, CAmount fee) {\n         Facts facts;\n         if (!node || !transaction) return facts;\n-        facts.within_fee_cap = !MoneyRange(fee) || fee <= MaxFee();\n+        facts.within_fee_cap = !enforce_raw_fee_cap || !MoneyRange(fee) || fee <= MaxFee();\n         if (chain && MoneyRange(fee)) {\n             try {\n                 const auto tip = node->getBestBlockHash();\n@@ -142,7 +143,7 @@ psbtpolicy::Read psbtpolicy::ReadNode(interfaces::Node* node, interfaces::Chain*\n             if (facts.observed && facts.tip != QString::fromStdString(admission_tip.ToString())) {\n                 ClearChainFacts(facts);\n             }\n-            ReadAdmission(*node, *transaction, facts);\n+            ReadAdmission(*node, *transaction, facts, enforce_raw_fee_cap);\n             // Drop both observations if the active tip changed while the RPC ran.\n             if (node->getBestBlockHash() != admission_tip) {\n                 ClearChainFacts(facts);\n@@ -162,7 +163,10 @@ psbtpolicy::Decision psbtpolicy::Evaluate(const Facts& facts)\n         if (facts.immature_inputs) return {State::Blocked, Tr(\"An input spends an immature coinbase output. Refresh the review after more blocks.\")};\n         if (!facts.final) return {State::Blocked, Tr(\"The transaction lock time is not final at the observed chain tip.\")};\n         if (!facts.sufficient_fee) return {State::Blocked, Tr(\"The fee is below the node's current advertised minimum.\")};\n-        if (!facts.chain_limits) return {State::Blocked, facts.chain_error.isEmpty() ? Tr(\"The transaction exceeds the node's current mempool chain limits.\") : facts.chain_error};\n+        // checkChainLimits does not account for conflicting transactions a\n+        // replacement would evict; when testmempoolaccept already allowed this\n+        // exact transaction, do not override it with the non-RBF chain check.\n+        if (!facts.chain_limits && facts.admission != Admission::Allowed) return {State::Blocked, facts.chain_error.isEmpty() ? Tr(\"The transaction exceeds the node's current mempool chain limits.\") : facts.chain_error};\n     }\n     if (!facts.within_fee_cap) return {State::Blocked, Tr(\"The fee is above the node's maximum of %1 for one transaction.\").arg(QmlBitcoinUnits::format(QmlBitcoinUnits::Unit::BTC, MaxFee()) + QStringLiteral(\" BTC\"))};\n     if (facts.admission == Admission::Rejected) {\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 187,
    "evidence_id": "cfe4034a7e954d4280b32e88f438ef58",
    "finding_id": "finding:10",
    "kind": "new_source",
    "line": 135,
    "new_head": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "old_head": "f28230183aa967642ad79f91d506ad151c1e3d35",
    "path": "qml/psbtpolicy.cpp",
    "revision": "97a21cf9cba76f0798b402c68b4a1fee52d7d046",
    "source_generation": 24,
    "source_job_id": 3164,
    "text": "                    }\n                }\n            } catch (...) {\n                ClearChainFacts(facts);\n            }\n        }\n        try {\n            const auto admission_tip = node->getBestBlockHash();\n            if (facts.observed && facts.tip != QString::fromStdString(admission_tip.ToString())) {\n                ClearChainFacts(facts);\n            }\n            ReadAdmission(*node, *transaction, facts, enforce_raw_fee_cap);\n            // Drop both observations if the active tip changed while the RPC ran.\n            if (node->getBestBlockHash() != admission_tip) {\n                ClearChainFacts(facts);\n                ClearAdmissionFacts(facts);\n            }\n        } catch (...) {\n            ClearAdmissionFacts(facts);\n        }\n        return facts;\n    };\n}\n\npsbtpolicy::Decision psbtpolicy::Evaluate(const Facts& facts)\n{\n    if (facts.observed) {\n        if (facts.missing_inputs) return {State::Blocked, Tr(\"An input is missing or already spent at the observed chain tip. Refresh the review before submitting.\")};\n        if (facts.immature_inputs) return {State::Blocked, Tr(\"An input spends an immature coinbase output. Refresh the review after more blocks.\")};\n        if (!facts.final) return {State::Blocked, Tr(\"The transaction lock time is not final at the observed chain tip.\")};\n        if (!facts.sufficient_fee) return {State::Blocked, Tr(\"The fee is below the node's current advertised minimum.\")};\n        // checkChainLimits does not account for conflicting transactions a\n        // replacement would evict; when testmempoolaccept already allowed this\n        // exact transaction, do not override it with the non-RBF chain check.\n        if (!facts.chain_limits && facts.admission != Admission::Allowed) return {State::Blocked, facts.chain_error.isEmpty() ? Tr(\"The transaction exceeds the node's current mempool chain limits.\") : facts.chain_error};\n    }\n    if (!facts.within_fee_cap) return {State::Blocked, Tr(\"The fee is above the node's maximum of %1 for one transaction.\").arg(QmlBitcoinUnits::format(QmlBitcoinUnits::Unit::BTC, MaxFee()) + QStringLiteral(\" BTC\"))};\n    if (facts.admission == Admission::Rejected) {\n        const QString reason = facts.admission_error.isEmpty() ? Tr(\"The node currently rejects this transaction.\") : facts.admission_error;\n        return {State::Blocked, reason};\n    }\n    if (facts.admission == Admission::Allowed) {\n        if (!facts.replaces.isEmpty()) {\n            return {State::NoKnownObstacle, Tr(\"The node currently accepts this exact transaction as a replacement. Submitting it removes unconfirmed transaction %1 from the mempool.\").arg(facts.replaces.join(QStringLiteral(\", \")))};\n        }\n        if (facts.replaces_unknown) {\n            return {State::NoKnownObstacle, Tr(\"The node currently accepts this exact transaction, but it could not be checked whether submitting it removes an unconfirmed transaction from the mempool. Submission will check current policy again.\")};\n        }\n        return {State::NoKnownObstacle, Tr(\"The node currently accepts this exact transaction. Submission will check current policy again.\")};\n    }\n    if (facts.observed) return {State::NoKnownObstacle, Tr(\"Fully signed. Read-only node checks found no obstacle; submission will check current policy, including conflicts and replacements.\")};\n    return {State::Unknown, Tr(\"Fully signed. Current node policy will be checked when you submit.\")};\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1142Failed signer approval can switch Save transaction back to PSBT v2qml/models/walletmodel.cppunclear
Assessment

The follow-up assessment was invalid: addressed findings require original comparison evidence.

invalid_assessment

Source report · f28230183aa9..97a21cf9cba7

2026-11-26T02:44:06Z · gpt-6-luna

gui#1144Wallet backups do not carry pending import recovery stateqml/walletqmlcontroller.cppaddressed
Assessment

The wallet model rejects backups while history recovery is nonempty, and the settings-page caller also displays a warning and stops before starting a backup.

path_diff: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "5024f33692994d25a06422bc10a97d07",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 5,
    "source_job_id": 3119,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 81317bf10e..08c013c361 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -145,7 +145,7 @@ QString PendingImportKey(const std::string& wallet_path)\n     return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n }\n \n-void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n+bool SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n     const QString key{PendingImportKey(wallet_path)};\n@@ -155,6 +155,7 @@ void SetPendingImport(const std::string& wallet_path, std::optional<PendingImpor\n         settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n+    return settings.status() == QSettings::NoError;\n }\n \n std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n@@ -205,13 +206,10 @@ ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& walle\n     const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n     if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n     if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n-    ImportRescanResult stopped{Status::Stopped};\n     int64_t last_time{0};\n-    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n-        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n-        stopped.checkpoint = last_time;\n-    }\n-    return stopped;\n+    const bool checkpoint{result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+                          wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))};\n+    return {Status::Stopped, checkpoint ? std::optional<int64_t>{last_time} : std::nullopt};\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -736,7 +734,8 @@ void WalletQmlController::createWalletAsync(const QString& name,\n                                             WalletLoadAction load_action,\n                                             bool report_create_error,\n                                             WalletSetupFn setup_wallet,\n-                                            WalletCheckFn check_before_create)\n+                                            WalletCheckFn check_before_create,\n+                                            std::shared_ptr<RescanControl> import_control)\n {\n     const QString wallet_name = name.trimmed();\n     if (setup_wallet) {\n@@ -769,10 +768,19 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             out.wallet = std::move(*wallet);\n         }\n         return out;\n-    }, [this, wallet_name, load_action, report_create_error](WalletCommandResult out) {\n+    }, [this, wallet_name, load_action, report_create_error, import_control](WalletCommandResult out) {\n         if (m_deferred_wallet_name == wallet_name) m_deferred_wallet_name.clear();\n         setWalletLoadWarnings(out.warnings);\n         setWalletLoadInProgress(false);\n+        // A cancel can arrive after the worker last checked for one.\n+        if (out.wallet && import_control && import_control->cancelled()) {\n+            setWalletLoadError(tr(\"The import was cancelled, and its wallet was deleted.\"));\n+            m_wallet_command_executor->submit(this, [node = &m_node, wallet = std::move(out.wallet), wallet_name]() mutable {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }, [] {});\n+            return;\n+        }\n         if (!out.wallet) {\n             if (report_create_error) setWalletCreateError(out.error);\n             else setWalletLoadError(out.error);\n@@ -924,16 +932,24 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                        bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n+        // The abort refers to this wallet, which is gone once this returns or throws.\n+        const auto detach{qScopeGuard([&control] { control->detach(); })};\n         const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n         // Resolved here, so the marker starts where the wallet's rescan does.\n         const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n-        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n+        // Without the marker, a crash during the rescan would leave the wallet missing history unnoticed.\n+        if (!SetPendingImport(path, PendingImport{start, /*installed=*/false})) {\n+            return WalletQmlController::tr(\"The app couldn't save its settings, which it needs to finish the import if it closes during it. Check that its settings can be written, then try again.\");\n+        }\n         std::vector<wallet::ImportResult> results;\n         {\n-            // The rescan starts once every descriptor is saved.\n-            bool installed{false};\n+            // The rescan starts after every request is handled, even when some failed.\n+            bool checked{false};\n             const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n-                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                if (!std::exchange(checked, true)) {\n+                    const wallet::CWallet* raw_wallet{wallet.wallet()};\n+                    if (raw_wallet && DescriptorsSaved(*raw_wallet, requests)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                }\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -943,7 +959,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             // Imports the descriptors, then rescans from the oldest timestamp.\n             results = wallet.importDescriptors(requests);\n         }\n-        control->detach();\n         if (control->cancelled()) return cancelled;\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n@@ -967,7 +982,7 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             return WalletQmlController::tr(\"This node no longer has the blocks from when this wallet was created, so it can't find the older transactions. Choose a later date, or import it on a node that keeps all blocks.\");\n         }\n         return QString{};\n-    });\n+    }, control);\n }\n \n void WalletQmlController::importWallet(const QString& path)\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 60c9d57773fb..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144Cancellation after the final worker check is ignoredqml/walletqmlcontroller.cppaddressed
Assessment

The wallet-creation GUI completion now checks the shared import control; if cancellation won after the worker's last check, it schedules disposal of the created wallet instead of publishing it.

path_diff: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "4bd59e1ad42a4cb8915a9d081df6718e",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 5,
    "source_job_id": 3119,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 81317bf10e..08c013c361 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -145,7 +145,7 @@ QString PendingImportKey(const std::string& wallet_path)\n     return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n }\n \n-void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n+bool SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n     const QString key{PendingImportKey(wallet_path)};\n@@ -155,6 +155,7 @@ void SetPendingImport(const std::string& wallet_path, std::optional<PendingImpor\n         settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n+    return settings.status() == QSettings::NoError;\n }\n \n std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n@@ -205,13 +206,10 @@ ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& walle\n     const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n     if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n     if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n-    ImportRescanResult stopped{Status::Stopped};\n     int64_t last_time{0};\n-    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n-        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n-        stopped.checkpoint = last_time;\n-    }\n-    return stopped;\n+    const bool checkpoint{result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+                          wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))};\n+    return {Status::Stopped, checkpoint ? std::optional<int64_t>{last_time} : std::nullopt};\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -736,7 +734,8 @@ void WalletQmlController::createWalletAsync(const QString& name,\n                                             WalletLoadAction load_action,\n                                             bool report_create_error,\n                                             WalletSetupFn setup_wallet,\n-                                            WalletCheckFn check_before_create)\n+                                            WalletCheckFn check_before_create,\n+                                            std::shared_ptr<RescanControl> import_control)\n {\n     const QString wallet_name = name.trimmed();\n     if (setup_wallet) {\n@@ -769,10 +768,19 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             out.wallet = std::move(*wallet);\n         }\n         return out;\n-    }, [this, wallet_name, load_action, report_create_error](WalletCommandResult out) {\n+    }, [this, wallet_name, load_action, report_create_error, import_control](WalletCommandResult out) {\n         if (m_deferred_wallet_name == wallet_name) m_deferred_wallet_name.clear();\n         setWalletLoadWarnings(out.warnings);\n         setWalletLoadInProgress(false);\n+        // A cancel can arrive after the worker last checked for one.\n+        if (out.wallet && import_control && import_control->cancelled()) {\n+            setWalletLoadError(tr(\"The import was cancelled, and its wallet was deleted.\"));\n+            m_wallet_command_executor->submit(this, [node = &m_node, wallet = std::move(out.wallet), wallet_name]() mutable {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }, [] {});\n+            return;\n+        }\n         if (!out.wallet) {\n             if (report_create_error) setWalletCreateError(out.error);\n             else setWalletLoadError(out.error);\n@@ -924,16 +932,24 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                        bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n+        // The abort refers to this wallet, which is gone once this returns or throws.\n+        const auto detach{qScopeGuard([&control] { control->detach(); })};\n         const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n         // Resolved here, so the marker starts where the wallet's rescan does.\n         const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n-        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n+        // Without the marker, a crash during the rescan would leave the wallet missing history unnoticed.\n+        if (!SetPendingImport(path, PendingImport{start, /*installed=*/false})) {\n+            return WalletQmlController::tr(\"The app couldn't save its settings, which it needs to finish the import if it closes during it. Check that its settings can be written, then try again.\");\n+        }\n         std::vector<wallet::ImportResult> results;\n         {\n-            // The rescan starts once every descriptor is saved.\n-            bool installed{false};\n+            // The rescan starts after every request is handled, even when some failed.\n+            bool checked{false};\n             const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n-                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                if (!std::exchange(checked, true)) {\n+                    const wallet::CWallet* raw_wallet{wallet.wallet()};\n+                    if (raw_wallet && DescriptorsSaved(*raw_wallet, requests)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                }\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -943,7 +959,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             // Imports the descriptors, then rescans from the oldest timestamp.\n             results = wallet.importDescriptors(requests);\n         }\n-        control->detach();\n         if (control->cancelled()) return cancelled;\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n@@ -967,7 +982,7 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             return WalletQmlController::tr(\"This node no longer has the blocks from when this wallet was created, so it can't find the older transactions. Choose a later date, or import it on a node that keeps all blocks.\");\n         }\n         return QString{};\n-    });\n+    }, control);\n }\n \n void WalletQmlController::importWallet(const QString& path)\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 60c9d57773fb..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144Long import rescans block switching to other walletsqml/walletqmlcontroller.cppstill_present
Assessment

The import still calls importDescriptors synchronously inside the wallet-creation command. The supplied change adds cancellation handling and recovery tracking but does not separate the scan from creation or make other wallets usable during it.

path_diff: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "2479a262a6c34323855f377858c6c903",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 5,
    "source_job_id": 3119,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 81317bf10e..08c013c361 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -145,7 +145,7 @@ QString PendingImportKey(const std::string& wallet_path)\n     return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n }\n \n-void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n+bool SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n     const QString key{PendingImportKey(wallet_path)};\n@@ -155,6 +155,7 @@ void SetPendingImport(const std::string& wallet_path, std::optional<PendingImpor\n         settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n+    return settings.status() == QSettings::NoError;\n }\n \n std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n@@ -205,13 +206,10 @@ ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& walle\n     const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n     if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n     if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n-    ImportRescanResult stopped{Status::Stopped};\n     int64_t last_time{0};\n-    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n-        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n-        stopped.checkpoint = last_time;\n-    }\n-    return stopped;\n+    const bool checkpoint{result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+                          wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))};\n+    return {Status::Stopped, checkpoint ? std::optional<int64_t>{last_time} : std::nullopt};\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -736,7 +734,8 @@ void WalletQmlController::createWalletAsync(const QString& name,\n                                             WalletLoadAction load_action,\n                                             bool report_create_error,\n                                             WalletSetupFn setup_wallet,\n-                                            WalletCheckFn check_before_create)\n+                                            WalletCheckFn check_before_create,\n+                                            std::shared_ptr<RescanControl> import_control)\n {\n     const QString wallet_name = name.trimmed();\n     if (setup_wallet) {\n@@ -769,10 +768,19 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             out.wallet = std::move(*wallet);\n         }\n         return out;\n-    }, [this, wallet_name, load_action, report_create_error](WalletCommandResult out) {\n+    }, [this, wallet_name, load_action, report_create_error, import_control](WalletCommandResult out) {\n         if (m_deferred_wallet_name == wallet_name) m_deferred_wallet_name.clear();\n         setWalletLoadWarnings(out.warnings);\n         setWalletLoadInProgress(false);\n+        // A cancel can arrive after the worker last checked for one.\n+        if (out.wallet && import_control && import_control->cancelled()) {\n+            setWalletLoadError(tr(\"The import was cancelled, and its wallet was deleted.\"));\n+            m_wallet_command_executor->submit(this, [node = &m_node, wallet = std::move(out.wallet), wallet_name]() mutable {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }, [] {});\n+            return;\n+        }\n         if (!out.wallet) {\n             if (report_create_error) setWalletCreateError(out.error);\n             else setWalletLoadError(out.error);\n@@ -924,16 +932,24 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                        bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n+        // The abort refers to this wallet, which is gone once this returns or throws.\n+        const auto detach{qScopeGuard([&control] { control->detach(); })};\n         const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n         // Resolved here, so the marker starts where the wallet's rescan does.\n         const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n-        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n+        // Without the marker, a crash during the rescan would leave the wallet missing history unnoticed.\n+        if (!SetPendingImport(path, PendingImport{start, /*installed=*/false})) {\n+            return WalletQmlController::tr(\"The app couldn't save its settings, which it needs to finish the import if it closes during it. Check that its settings can be written, then try again.\");\n+        }\n         std::vector<wallet::ImportResult> results;\n         {\n-            // The rescan starts once every descriptor is saved.\n-            bool installed{false};\n+            // The rescan starts after every request is handled, even when some failed.\n+            bool checked{false};\n             const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n-                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                if (!std::exchange(checked, true)) {\n+                    const wallet::CWallet* raw_wallet{wallet.wallet()};\n+                    if (raw_wallet && DescriptorsSaved(*raw_wallet, requests)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                }\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -943,7 +959,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             // Imports the descriptors, then rescans from the oldest timestamp.\n             results = wallet.importDescriptors(requests);\n         }\n-        control->detach();\n         if (control->cancelled()) return cancelled;\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n@@ -967,7 +982,7 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             return WalletQmlController::tr(\"This node no longer has the blocks from when this wallet was created, so it can't find the older transactions. Choose a later date, or import it on a node that keeps all blocks.\");\n         }\n         return QString{};\n-    });\n+    }, control);\n }\n \n void WalletQmlController::importWallet(const QString& path)\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 60c9d57773fb..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144Import proceeds without confirming recovery-marker persistenceqml/walletqmlcontroller.cppaddressed
Assessment

SetPendingImport now reports QSettings persistence status, and setup returns a recoverable error before importing descriptors if the initial pending marker cannot be saved.

path_diff: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "bbd04bf6509b4b9a85eecf074514f624",
    "finding_id": "finding:4",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 5,
    "source_job_id": 3119,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 81317bf10e..08c013c361 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -145,7 +145,7 @@ QString PendingImportKey(const std::string& wallet_path)\n     return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n }\n \n-void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n+bool SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n     const QString key{PendingImportKey(wallet_path)};\n@@ -155,6 +155,7 @@ void SetPendingImport(const std::string& wallet_path, std::optional<PendingImpor\n         settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n+    return settings.status() == QSettings::NoError;\n }\n \n std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n@@ -205,13 +206,10 @@ ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& walle\n     const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n     if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n     if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n-    ImportRescanResult stopped{Status::Stopped};\n     int64_t last_time{0};\n-    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n-        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n-        stopped.checkpoint = last_time;\n-    }\n-    return stopped;\n+    const bool checkpoint{result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+                          wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))};\n+    return {Status::Stopped, checkpoint ? std::optional<int64_t>{last_time} : std::nullopt};\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -736,7 +734,8 @@ void WalletQmlController::createWalletAsync(const QString& name,\n                                             WalletLoadAction load_action,\n                                             bool report_create_error,\n                                             WalletSetupFn setup_wallet,\n-                                            WalletCheckFn check_before_create)\n+                                            WalletCheckFn check_before_create,\n+                                            std::shared_ptr<RescanControl> import_control)\n {\n     const QString wallet_name = name.trimmed();\n     if (setup_wallet) {\n@@ -769,10 +768,19 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             out.wallet = std::move(*wallet);\n         }\n         return out;\n-    }, [this, wallet_name, load_action, report_create_error](WalletCommandResult out) {\n+    }, [this, wallet_name, load_action, report_create_error, import_control](WalletCommandResult out) {\n         if (m_deferred_wallet_name == wallet_name) m_deferred_wallet_name.clear();\n         setWalletLoadWarnings(out.warnings);\n         setWalletLoadInProgress(false);\n+        // A cancel can arrive after the worker last checked for one.\n+        if (out.wallet && import_control && import_control->cancelled()) {\n+            setWalletLoadError(tr(\"The import was cancelled, and its wallet was deleted.\"));\n+            m_wallet_command_executor->submit(this, [node = &m_node, wallet = std::move(out.wallet), wallet_name]() mutable {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }, [] {});\n+            return;\n+        }\n         if (!out.wallet) {\n             if (report_create_error) setWalletCreateError(out.error);\n             else setWalletLoadError(out.error);\n@@ -924,16 +932,24 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                        bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n+        // The abort refers to this wallet, which is gone once this returns or throws.\n+        const auto detach{qScopeGuard([&control] { control->detach(); })};\n         const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n         // Resolved here, so the marker starts where the wallet's rescan does.\n         const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n-        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n+        // Without the marker, a crash during the rescan would leave the wallet missing history unnoticed.\n+        if (!SetPendingImport(path, PendingImport{start, /*installed=*/false})) {\n+            return WalletQmlController::tr(\"The app couldn't save its settings, which it needs to finish the import if it closes during it. Check that its settings can be written, then try again.\");\n+        }\n         std::vector<wallet::ImportResult> results;\n         {\n-            // The rescan starts once every descriptor is saved.\n-            bool installed{false};\n+            // The rescan starts after every request is handled, even when some failed.\n+            bool checked{false};\n             const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n-                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                if (!std::exchange(checked, true)) {\n+                    const wallet::CWallet* raw_wallet{wallet.wallet()};\n+                    if (raw_wallet && DescriptorsSaved(*raw_wallet, requests)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                }\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -943,7 +959,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             // Imports the descriptors, then rescans from the oldest timestamp.\n             results = wallet.importDescriptors(requests);\n         }\n-        control->detach();\n         if (control->cancelled()) return cancelled;\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n@@ -967,7 +982,7 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             return WalletQmlController::tr(\"This node no longer has the blocks from when this wallet was created, so it can't find the older transactions. Choose a later date, or import it on a node that keeps all blocks.\");\n         }\n         return QString{};\n-    });\n+    }, control);\n }\n \n void WalletQmlController::importWallet(const QString& path)\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 60c9d57773fb..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144Rescan progress incorrectly certifies complete descriptor installationqml/walletqmlcontroller.cppaddressed
Assessment

The marker is promoted to installed only after DescriptorsSaved verifies each requested descriptor and each path of a multipath descriptor; progress events alone no longer certify installation.

path_diff: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "1336b34e69a946628cb99ed7ab470461",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 5,
    "source_job_id": 3119,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 81317bf10e..08c013c361 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -145,7 +145,7 @@ QString PendingImportKey(const std::string& wallet_path)\n     return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n }\n \n-void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n+bool SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n     const QString key{PendingImportKey(wallet_path)};\n@@ -155,6 +155,7 @@ void SetPendingImport(const std::string& wallet_path, std::optional<PendingImpor\n         settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n+    return settings.status() == QSettings::NoError;\n }\n \n std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n@@ -205,13 +206,10 @@ ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& walle\n     const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n     if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n     if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n-    ImportRescanResult stopped{Status::Stopped};\n     int64_t last_time{0};\n-    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n-        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n-        stopped.checkpoint = last_time;\n-    }\n-    return stopped;\n+    const bool checkpoint{result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+                          wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))};\n+    return {Status::Stopped, checkpoint ? std::optional<int64_t>{last_time} : std::nullopt};\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -736,7 +734,8 @@ void WalletQmlController::createWalletAsync(const QString& name,\n                                             WalletLoadAction load_action,\n                                             bool report_create_error,\n                                             WalletSetupFn setup_wallet,\n-                                            WalletCheckFn check_before_create)\n+                                            WalletCheckFn check_before_create,\n+                                            std::shared_ptr<RescanControl> import_control)\n {\n     const QString wallet_name = name.trimmed();\n     if (setup_wallet) {\n@@ -769,10 +768,19 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             out.wallet = std::move(*wallet);\n         }\n         return out;\n-    }, [this, wallet_name, load_action, report_create_error](WalletCommandResult out) {\n+    }, [this, wallet_name, load_action, report_create_error, import_control](WalletCommandResult out) {\n         if (m_deferred_wallet_name == wallet_name) m_deferred_wallet_name.clear();\n         setWalletLoadWarnings(out.warnings);\n         setWalletLoadInProgress(false);\n+        // A cancel can arrive after the worker last checked for one.\n+        if (out.wallet && import_control && import_control->cancelled()) {\n+            setWalletLoadError(tr(\"The import was cancelled, and its wallet was deleted.\"));\n+            m_wallet_command_executor->submit(this, [node = &m_node, wallet = std::move(out.wallet), wallet_name]() mutable {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }, [] {});\n+            return;\n+        }\n         if (!out.wallet) {\n             if (report_create_error) setWalletCreateError(out.error);\n             else setWalletLoadError(out.error);\n@@ -924,16 +932,24 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                        bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n+        // The abort refers to this wallet, which is gone once this returns or throws.\n+        const auto detach{qScopeGuard([&control] { control->detach(); })};\n         const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n         // Resolved here, so the marker starts where the wallet's rescan does.\n         const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n-        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n+        // Without the marker, a crash during the rescan would leave the wallet missing history unnoticed.\n+        if (!SetPendingImport(path, PendingImport{start, /*installed=*/false})) {\n+            return WalletQmlController::tr(\"The app couldn't save its settings, which it needs to finish the import if it closes during it. Check that its settings can be written, then try again.\");\n+        }\n         std::vector<wallet::ImportResult> results;\n         {\n-            // The rescan starts once every descriptor is saved.\n-            bool installed{false};\n+            // The rescan starts after every request is handled, even when some failed.\n+            bool checked{false};\n             const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n-                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                if (!std::exchange(checked, true)) {\n+                    const wallet::CWallet* raw_wallet{wallet.wallet()};\n+                    if (raw_wallet && DescriptorsSaved(*raw_wallet, requests)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                }\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -943,7 +959,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             // Imports the descriptors, then rescans from the oldest timestamp.\n             results = wallet.importDescriptors(requests);\n         }\n-        control->detach();\n         if (control->cancelled()) return cancelled;\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n@@ -967,7 +982,7 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             return WalletQmlController::tr(\"This node no longer has the blocks from when this wallet was created, so it can't find the older transactions. Choose a later date, or import it on a node that keeps all blocks.\");\n         }\n         return QString{};\n-    });\n+    }, control);\n }\n \n void WalletQmlController::importWallet(const QString& path)\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 60c9d57773fb..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144High-start descriptor ranges trigger enormous uncancellable importsqml/viewonlyimport.cppaddressed
Assessment

JSON descriptor ranges ending at or above 1,000,000 are rejected before import with an explanatory error, bounding the derivation work that previously could run into billions of indexes.

path_diff: qml/viewonlyimport.cpp

[
  {
    "evidence_id": "b1fd97d298c84e3fbf43870999b6f239",
    "finding_id": "finding:2",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "path": "qml/viewonlyimport.cpp",
    "source_generation": 5,
    "source_job_id": 3119,
    "text": "diff --git a/qml/viewonlyimport.cpp b/qml/viewonlyimport.cpp\nindex 145f14baa5..12e54f0f5b 100644\n--- a/qml/viewonlyimport.cpp\n+++ b/qml/viewonlyimport.cpp\n@@ -31,6 +31,9 @@\n \n using wallet::ImportDescriptorRequest;\n \n+// As many keys as the wallet allows in one range.\n+constexpr int64_t MAX_RANGE_END{1'000'000};\n+\n namespace {\n \n struct DescriptorCheck {\n@@ -201,6 +204,12 @@ ViewOnlyImport ParseJson(const std::string& text)\n                 if (const auto bounds{CheckDescriptorRangeBounds(request.range->first, request.range->second)}; !bounds) {\n                     return Failed(Kind::DescriptorJson, QStringLiteral(\"%1: %2\").arg(position, QString::fromStdString(bounds.error())));\n                 }\n+                // The wallet derives every key from index 0 to the end, while it blocks and can't be cancelled.\n+                if (request.range->second >= MAX_RANGE_END) {\n+                    //: %2 is the highest index that can be imported.\n+                    return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a range that ends after %2, which would take too long to set up.\")\n+                                                            .arg(position).arg(MAX_RANGE_END - 1));\n+                }\n             }\n             const UniValue& next_index{entry.find_value(\"next_index\")};\n             const UniValue& next{next_index.isNull() ? entry.find_value(\"next\") : next_index};\n@@ -574,3 +583,18 @@ int64_t ResolveImportTimes(std::vector<ImportDescriptorRequest>& requests, int64\n     }\n     return oldest;\n }\n+\n+bool DescriptorsSaved(const wallet::CWallet& wallet, const std::vector<ImportDescriptorRequest>& requests)\n+{\n+    LOCK(wallet.cs_wallet);\n+    for (const ImportDescriptorRequest& request : requests) {\n+        FlatSigningProvider keys;\n+        std::string error;\n+        auto parsed{Parse(request.descriptor, keys, error, /*require_checksum=*/false)};\n+        if (parsed.empty()) return false;\n+        for (auto& descriptor : parsed) {\n+            if (!wallet.GetDescriptorScriptPubKeyMan(wallet::WalletDescriptor{std::move(descriptor), 0, 0, 0, 0})) return false;\n+        }\n+    }\n+    return true;\n+}\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 60c9d57773fb..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144Import exceptions leave a dangling abort callbackqml/walletqmlcontroller.cppaddressed
Assessment

A scope guard is installed immediately after successful attachment, so every exit, including an exception from descriptor import, detaches the abort callback before the wallet interface is destroyed.

path_diff: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "addc589f92174465920b9ee745d59504",
    "finding_id": "finding:1",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 5,
    "source_job_id": 3119,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 81317bf10e..08c013c361 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -145,7 +145,7 @@ QString PendingImportKey(const std::string& wallet_path)\n     return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n }\n \n-void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n+bool SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n     const QString key{PendingImportKey(wallet_path)};\n@@ -155,6 +155,7 @@ void SetPendingImport(const std::string& wallet_path, std::optional<PendingImpor\n         settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n+    return settings.status() == QSettings::NoError;\n }\n \n std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n@@ -205,13 +206,10 @@ ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& walle\n     const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n     if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n     if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n-    ImportRescanResult stopped{Status::Stopped};\n     int64_t last_time{0};\n-    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n-        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n-        stopped.checkpoint = last_time;\n-    }\n-    return stopped;\n+    const bool checkpoint{result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+                          wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))};\n+    return {Status::Stopped, checkpoint ? std::optional<int64_t>{last_time} : std::nullopt};\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -736,7 +734,8 @@ void WalletQmlController::createWalletAsync(const QString& name,\n                                             WalletLoadAction load_action,\n                                             bool report_create_error,\n                                             WalletSetupFn setup_wallet,\n-                                            WalletCheckFn check_before_create)\n+                                            WalletCheckFn check_before_create,\n+                                            std::shared_ptr<RescanControl> import_control)\n {\n     const QString wallet_name = name.trimmed();\n     if (setup_wallet) {\n@@ -769,10 +768,19 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             out.wallet = std::move(*wallet);\n         }\n         return out;\n-    }, [this, wallet_name, load_action, report_create_error](WalletCommandResult out) {\n+    }, [this, wallet_name, load_action, report_create_error, import_control](WalletCommandResult out) {\n         if (m_deferred_wallet_name == wallet_name) m_deferred_wallet_name.clear();\n         setWalletLoadWarnings(out.warnings);\n         setWalletLoadInProgress(false);\n+        // A cancel can arrive after the worker last checked for one.\n+        if (out.wallet && import_control && import_control->cancelled()) {\n+            setWalletLoadError(tr(\"The import was cancelled, and its wallet was deleted.\"));\n+            m_wallet_command_executor->submit(this, [node = &m_node, wallet = std::move(out.wallet), wallet_name]() mutable {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }, [] {});\n+            return;\n+        }\n         if (!out.wallet) {\n             if (report_create_error) setWalletCreateError(out.error);\n             else setWalletLoadError(out.error);\n@@ -924,16 +932,24 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                        bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n+        // The abort refers to this wallet, which is gone once this returns or throws.\n+        const auto detach{qScopeGuard([&control] { control->detach(); })};\n         const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n         // Resolved here, so the marker starts where the wallet's rescan does.\n         const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n-        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n+        // Without the marker, a crash during the rescan would leave the wallet missing history unnoticed.\n+        if (!SetPendingImport(path, PendingImport{start, /*installed=*/false})) {\n+            return WalletQmlController::tr(\"The app couldn't save its settings, which it needs to finish the import if it closes during it. Check that its settings can be written, then try again.\");\n+        }\n         std::vector<wallet::ImportResult> results;\n         {\n-            // The rescan starts once every descriptor is saved.\n-            bool installed{false};\n+            // The rescan starts after every request is handled, even when some failed.\n+            bool checked{false};\n             const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n-                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                if (!std::exchange(checked, true)) {\n+                    const wallet::CWallet* raw_wallet{wallet.wallet()};\n+                    if (raw_wallet && DescriptorsSaved(*raw_wallet, requests)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                }\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -943,7 +959,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             // Imports the descriptors, then rescans from the oldest timestamp.\n             results = wallet.importDescriptors(requests);\n         }\n-        control->detach();\n         if (control->cancelled()) return cancelled;\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n@@ -967,7 +982,7 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             return WalletQmlController::tr(\"This node no longer has the blocks from when this wallet was created, so it can't find the older transactions. Choose a later date, or import it on a node that keeps all blocks.\");\n         }\n         return QString{};\n-    });\n+    }, control);\n }\n \n void WalletQmlController::importWallet(const QString& path)\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 60c9d57773fb..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144next_index without range bypasses pre-import bounds checkingqml/viewonlyimport.cppaddressed
Assessment

JSON validation now rejects any next_index without an explicit range and checks the index against the supplied range before wallet creation.

path_diff: qml/viewonlyimport.cpp; new_source: qml/viewonlyimport.cpp

[
  {
    "evidence_id": "e2e7c9be513b4982bc4322a4cb385696",
    "finding_id": "finding:9",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/viewonlyimport.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/viewonlyimport.cpp b/qml/viewonlyimport.cpp\nindex 4dbb3041d2..145f14baa5 100644\n--- a/qml/viewonlyimport.cpp\n+++ b/qml/viewonlyimport.cpp\n@@ -220,9 +220,12 @@ ViewOnlyImport ParseJson(const std::string& text)\n             if (!request.label.empty() && (check.ranged || multipath || request.internal.value_or(false))) {\n                 return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a label, but only a single receive address can have one.\").arg(position));\n             }\n+            // Without a range, the wallet's keypool size bounds it, which isn't known here.\n+            if (request.next_index && !request.range) {\n+                return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index but no range.\").arg(position));\n+            }\n             if (check.ranged && request.next_index) {\n-                const int64_t first{request.range ? request.range->first : 0};\n-                if (*request.next_index < first || (request.range && *request.next_index > request.range->second)) {\n+                if (*request.next_index < request.range->first || *request.next_index > request.range->second) {\n                     return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index outside its range.\").arg(position));\n                 }\n             }\n@@ -321,6 +324,8 @@ const std::array KNOWN_KEY_VERSIONS{\n // [fingerprint/path]key, the key origin form wallets export.\n const QRegularExpression KEY_ORIGIN{QStringLiteral(R\"(^\\[([0-9a-fA-F]{8})((?:/[0-9]+['hH]?)*)\\]([1-9A-HJ-NP-Za-km-z]+)$)\")};\n const QRegularExpression ORIGIN_PURPOSE{QStringLiteral(R\"(^/(44|49|84|86)['hH])\")};\n+// BIP45 and BIP48 are multisig cosigner paths.\n+const QRegularExpression MULTISIG_PURPOSE{QStringLiteral(R\"(^/(45|48)['hH])\")};\n \n struct ExtendedKey {\n     bool recognized{false};\n@@ -394,6 +399,9 @@ ViewOnlyImport ParseExtendedKey(const ExtendedKey& key, const QString& origin, c\n {\n     using Kind = ViewOnlyImport::Kind;\n     if (!key.error.isEmpty()) return Failed(Kind::ExtendedKey, key.error);\n+    if (MULTISIG_PURPOSE.match(path).hasMatch()) {\n+        return Failed(Kind::ExtendedKey, QObject::tr(\"This key is from a multisig wallet. Only single-key wallets can be imported.\"));\n+    }\n     // The key's prefix wins, then a BIP44, 49, 84 or 86 path.\n     const std::optional<OutputType> path_type{PurposeType(path)};\n     std::optional<OutputType> type{key.type ? key.type : path_type};\n@@ -476,8 +484,10 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n             active_slots[{type, request.internal.value_or(false)}] = i;\n         }\n     }\n-    std::vector<bool> active(parsed.requests.size(), false);\n-    for (const auto& [slot, index] : active_slots) active[index] = true;\n+    const auto branch_active = [&](size_t i, bool change) {\n+        const auto slot{active_slots.find({parsed.sources[i].type, change})};\n+        return slot != active_slots.end() && slot->second == i;\n+    };\n     QString warning{parsed.warning};\n     if (warning.isEmpty() && std::ranges::none_of(active_slots, [](const auto& slot) { return slot.first.second; })) {\n         bool watches_change{false};\n@@ -489,7 +499,7 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n             : QObject::tr(\"Nothing here is for change addresses. Payments to the other wallet's change won't show, and this wallet can't prepare a transaction that needs change.\");\n     }\n \n-    // Receive and change of one key share a row.\n+    // Receive and change of one key share a row, unless only one of them stays active.\n     QVariantList rows;\n     QStringList row_keys;\n     for (size_t i = 0; i < parsed.requests.size(); ++i) {\n@@ -501,34 +511,36 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n         if (time) created = std::min(created.value_or(*time), *time);\n \n         const QString type{QmlUtil::OutputTypeLabel(source.type)};\n-        auto row_it{rows.begin()};\n-        for (; row_it != rows.end(); ++row_it) {\n-            const QVariantMap map{row_it->toMap()};\n-            if (map.value(QStringLiteral(\"addressType\")) == type && row_keys[std::distance(rows.begin(), row_it)] == source.key_id &&\n-                map.value(QStringLiteral(\"active\")) == bool(active[i]) && map.value(QStringLiteral(\"ranged\")) == source.ranged) {\n-                break;\n+        const std::vector<bool> branches{source.multipath ? std::vector<bool>{false, true} : std::vector<bool>{request.internal.value_or(false)}};\n+        for (const bool change : branches) {\n+            const bool active{branch_active(i, change)};\n+            auto row_it{rows.begin()};\n+            for (; row_it != rows.end(); ++row_it) {\n+                const QVariantMap map{row_it->toMap()};\n+                if (map.value(QStringLiteral(\"addressType\")) == type && row_keys[std::distance(rows.begin(), row_it)] == source.key_id &&\n+                    map.value(QStringLiteral(\"active\")) == active && map.value(QStringLiteral(\"ranged\")) == source.ranged) {\n+                    break;\n+                }\n             }\n+            if (row_it == rows.end()) {\n+                row_keys.append(source.key_id);\n+                rows.append(QVariantMap{{QStringLiteral(\"addressType\"), type},\n+                                        {QStringLiteral(\"key\"), source.key},\n+                                        {QStringLiteral(\"receive\"), false},\n+                                        {QStringLiteral(\"change\"), false},\n+                                        {QStringLiteral(\"active\"), active},\n+                                        {QStringLiteral(\"ranged\"), source.ranged},\n+                                        {QStringLiteral(\"createdTime\"), qlonglong(-1)}});\n+                row_it = std::prev(rows.end());\n+            }\n+            QVariantMap row{row_it->toMap()};\n+            row.insert(change ? QStringLiteral(\"change\") : QStringLiteral(\"receive\"), true);\n+            if (time) {\n+                const qlonglong row_time{row.value(QStringLiteral(\"createdTime\")).toLongLong()};\n+                row.insert(QStringLiteral(\"createdTime\"), row_time < 0 ? qlonglong(*time) : std::min(row_time, qlonglong(*time)));\n+            }\n+            *row_it = row;\n         }\n-        if (row_it == rows.end()) {\n-            row_keys.append(source.key_id);\n-            rows.append(QVariantMap{{QStringLiteral(\"addressType\"), type},\n-                                    {QStringLiteral(\"key\"), source.key},\n-                                    {QStringLiteral(\"receive\"), false},\n-                                    {QStringLiteral(\"change\"), false},\n-                                    {QStringLiteral(\"active\"), bool(active[i])},\n-                                    {QStringLiteral(\"ranged\"), source.ranged},\n-                                    {QStringLiteral(\"createdTime\"), qlonglong(-1)}});\n-            row_it = std::prev(rows.end());\n-        }\n-        QVariantMap row{row_it->toMap()};\n-        const bool change{request.internal.value_or(false)};\n-        if (source.multipath || !change) row.insert(QStringLiteral(\"receive\"), true);\n-        if (source.multipath || change) row.insert(QStringLiteral(\"change\"), true);\n-        if (time) {\n-            const qlonglong row_time{row.value(QStringLiteral(\"createdTime\")).toLongLong()};\n-            row.insert(QStringLiteral(\"createdTime\"), row_time < 0 ? qlonglong(*time) : std::min(row_time, qlonglong(*time)));\n-        }\n-        *row_it = row;\n     }\n     QStringList descriptors;\n     for (const ImportDescriptorRequest& request : parsed.requests) descriptors.append(QString::fromStdString(request.descriptor));\n@@ -552,3 +564,13 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n     }\n     return result;\n }\n+\n+int64_t ResolveImportTimes(std::vector<ImportDescriptorRequest>& requests, int64_t now)\n+{\n+    int64_t oldest{now};\n+    for (ImportDescriptorRequest& request : requests) {\n+        request.timestamp = request.timestamp.value_or(now);\n+        oldest = std::min(oldest, *request.timestamp);\n+    }\n+    return oldest;\n+}\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 344,
    "evidence_id": "aacf4876345c42d689e9e07d1100589b",
    "finding_id": "finding:9",
    "kind": "new_source",
    "line": 195,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/viewonlyimport.cpp",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "            if (const UniValue& active{entry.find_value(\"active\")}; !active.isNull()) request.active = active.get_bool();\n            if (const UniValue& internal{entry.find_value(\"internal\")}; !internal.isNull()) request.internal = internal.get_bool();\n            if (const UniValue& label{entry.find_value(\"label\")}; !label.isNull()) request.label = label.get_str();\n            if (const UniValue& range{entry.find_value(\"range\")}; !range.isNull()) {\n                request.range = ReadRange(range);\n                if (!request.range) return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has an invalid range.\").arg(position));\n                if (const auto bounds{CheckDescriptorRangeBounds(request.range->first, request.range->second)}; !bounds) {\n                    return Failed(Kind::DescriptorJson, QStringLiteral(\"%1: %2\").arg(position, QString::fromStdString(bounds.error())));\n                }\n            }\n            const UniValue& next_index{entry.find_value(\"next_index\")};\n            const UniValue& next{next_index.isNull() ? entry.find_value(\"next\") : next_index};\n            if (!next.isNull()) request.next_index = next.getInt<int64_t>();\n\n            // The same checks the wallet makes, before the wallet file is created.\n            const bool multipath{check.count > 1};\n            if (request.active && !check.ranged) {\n                return Failed(Kind::DescriptorJson, QObject::tr(\"%1 is active, but only a ranged descriptor can be.\").arg(position));\n            }\n            if (request.range && !check.ranged) {\n                return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a range, but it is not ranged.\").arg(position));\n            }\n            if (request.internal && multipath) {\n                return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has receive and change paths, so it can't also set \\\"internal\\\".\").arg(position));\n            }\n            if (!request.label.empty() && (check.ranged || multipath || request.internal.value_or(false))) {\n                return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a label, but only a single receive address can have one.\").arg(position));\n            }\n            // Without a range, the wallet's keypool size bounds it, which isn't known here.\n            if (request.next_index && !request.range) {\n                return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index but no range.\").arg(position));\n            }\n            if (check.ranged && request.next_index) {\n                if (*request.next_index < request.range->first || *request.next_index > request.range->second) {\n                    return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index outside its range.\").arg(position));\n                }\n            }\n            // The wallet applies a repeated descriptor again, so a later copy can turn off an earlier one.\n            for (size_t p = 0; p < check.paths.size(); ++p) {\n                const std::pair settings{request.active, multipath ? p == 1 : request.internal.value_or(false)};\n                const auto [it, added]{path_settings.try_emplace(check.paths[p], settings)};\n                if (!added && it->second != settings) {\n                    return Failed(Kind::DescriptorJson, QObject::tr(\"%1 repeats an earlier descriptor with other settings.\").arg(position));\n                }\n            }\n\n            result.requests.push_back(std::move(request));\n            result.sources.push_back(check.source);\n            AddTypes(result, check);\n        } catch (const std::exception&) {\n            return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a field of the wrong type.\").arg(position));\n        }\n    }\n    if (std::ranges::none_of(result.requests, &ImportDescriptorRequest::active)) {\n        return Failed(Kind::DescriptorJson, QObject::tr(\"None of these descriptors is active, so the wallet could not give out addresses.\"));\n    }\n    return result;\n}\n\nViewOnlyImport ParseLines(const QStringList& lines)\n{\n    using Kind = ViewOnlyImport::Kind;\n    ViewOnlyImport result;\n    result.kind = Kind::Descriptors;\n    const qsizetype filled{std::ranges::count_if(lines, [](const QString& line) { return !line.trimmed().isEmpty(); })};\n    for (qsizetype i = 0; i < lines.size(); ++i) {\n        const QString line{lines[i].trimmed()};\n        if (line.isEmpty()) continue;\n        if (filled == 1 && !line.contains(QLatin1Char('('))) {\n            return Failed(Kind::Descriptors, QObject::tr(\"Enter descriptors, or an extended public key (xpub).\"));\n        }\n        const DescriptorCheck check{CheckDescriptor(line.toStdString())};\n        if (!check.error.isEmpty()) {\n            //: %1 is a line number, %2 explains what is wrong with that line.\n            ViewOnlyImport failed{Failed(Kind::Descriptors, filled == 1 ? check.error : QObject::tr(\"Line %1: %2\").arg(i + 1).arg(check.error))};\n            failed.error_line = int(i);\n            return failed;\n        }\n        ImportDescriptorRequest request;\n        request.descriptor = check.descriptor;\n        request.active = check.ranged;\n        // A multipath descriptor sets receive and change itself.\n        if (check.ranged && check.count == 1) request.internal = check.change_chain;\n        result.undated.push_back(result.requests.size());\n        result.requests.push_back(std::move(request));\n        result.sources.push_back(check.source);\n        AddTypes(result, check);\n    }\n    if (std::ranges::none_of(result.requests, &ImportDescriptorRequest::active)) {\n        return Failed(Kind::Descriptors, QObject::tr(\"Add a ranged descriptor, one ending in /*, so the wallet can give out addresses.\"));\n    }\n    return result;\n}\n\nusing KeyVersion = std::array<unsigned char, 4>;\n\nstruct KnownKeyVersion {\n    KeyVersion version;\n    //! Testnet, signet and regtest share these.\n    bool test;\n    bool is_private;\n    bool multisig;\n    std::optional<OutputType> type;\n};\n\n// BIP32 and SLIP-132 versions. The prefix of a ypub or zpub names its script type.\nconst std::array KNOWN_KEY_VERSIONS{\n    KnownKeyVersion{{0x04, 0x88, 0xb2, 0x1e}, false, false, false, std::nullopt},             // xpub\n    KnownKeyVersion{{0x04, 0x9d, 0x7c, 0xb2}, false, false, false, OutputType::P2SH_SEGWIT},  // ypub\n    KnownKeyVersion{{0x04, 0xb2, 0x47, 0x46}, false, false, false, OutputType::BECH32},       // zpub\n    KnownKeyVersion{{0x02, 0x95, 0xb4, 0x3f}, false, false, true, std::nullopt},              // Ypub\n    KnownKeyVersion{{0x02, 0xaa, 0x7e, 0xd3}, false, false, true, std::nullopt},              // Zpub\n    KnownKeyVersion{{0x04, 0x35, 0x87, 0xcf}, true, false, false, std::nullopt},              // tpub\n    KnownKeyVersion{{0x04, 0x4a, 0x52, 0x62}, true, false, false, OutputType::P2SH_SEGWIT},   // upub\n    KnownKeyVersion{{0x04, 0x5f, 0x1c, 0xf6}, true, false, false, OutputType::BECH32},        // vpub\n    KnownKeyVersion{{0x02, 0x42, 0x89, 0xef}, true, false, true, std::nullopt},               // Upub\n    KnownKeyVersion{{0x02, 0x57, 0x54, 0x83}, true, false, true, std::nullopt},               // Vpub\n    KnownKeyVersion{{0x04, 0x88, 0xad, 0xe4}, false, true, false, std::nullopt},              // xprv\n    KnownKeyVersion{{0x04, 0x9d, 0x78, 0x78}, false, true, false, std::nullopt},              // yprv\n    KnownKeyVersion{{0x04, 0xb2, 0x43, 0x0c}, false, true, false, std::nullopt},              // zprv\n    KnownKeyVersion{{0x02, 0x95, 0xb0, 0x05}, false, true, true, std::nullopt},               // Yprv\n    KnownKeyVersion{{0x02, 0xaa, 0x7a, 0x99}, false, true, true, std::nullopt},               // Zprv\n    KnownKeyVersion{{0x04, 0x35, 0x83, 0x94}, true, true, false, std::nullopt},               // tprv\n    KnownKeyVersion{{0x04, 0x4a, 0x4e, 0x28}, true, true, false, std::nullopt},               // uprv\n    KnownKeyVersion{{0x04, 0x5f, 0x18, 0xbc}, true, true, false, std::nullopt},               // vprv\n    KnownKeyVersion{{0x02, 0x42, 0x85, 0xb5}, true, true, true, std::nullopt},                // Uprv\n    KnownKeyVersion{{0x02, 0x57, 0x50, 0x48}, true, true, true, std::nullopt},                // Vprv\n};\n\n// [fingerprint/path]key, the key origin form wallets export.\nconst QRegularExpression KEY_ORIGIN{QStringLiteral(R\"(^\\[([0-9a-fA-F]{8})((?:/[0-9]+['hH]?)*)\\]([1-9A-HJ-NP-Za-km-z]+)$)\")};\nconst QRegularExpression ORIGIN_PURPOSE{QStringLiteral(R\"(^/(44|49|84|86)['hH])\")};\n// BIP45 and BIP48 are multisig cosigner paths.\nconst QRegularExpression MULTISIG_PURPOSE{QStringLiteral(R\"(^/(45|48)['hH])\")};\n\nstruct ExtendedKey {\n    bool recognized{false};\n    QString error;\n    //! The key with this network's xpub or tpub version.\n    std::string key;\n    std::optional<OutputType> type;\n};\n\nExtendedKey ReadExtendedKey(const std::string& text)\n{\n    std::vector<unsigned char> data;\n    if (!DecodeBase58Check(text, data, BIP32_EXTKEY_WITH_VERSION_SIZE) || data.size() != BIP32_EXTKEY_WITH_VERSION_SIZE) return {};\n    const auto known{std::ranges::find_if(KNOWN_KEY_VERSIONS, [&](const KnownKeyVersion& known) {\n        return std::equal(known.version.begin(), known.version.end(), data.begin());\n    })};",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1144BIP48 cosigner origins are treated as single-key importsqml/viewonlyimport.cppaddressed
Assessment

The new multisig-purpose matcher recognizes BIP45 and BIP48 origins, and parsing rejects these keys with the multisig-only rejection message before offering an address-type choice.

path_diff: qml/viewonlyimport.cpp; new_source: qml/viewonlyimport.cpp

[
  {
    "evidence_id": "49ae8b480a464f9bb1f6378f5cae03a6",
    "finding_id": "finding:8",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/viewonlyimport.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/viewonlyimport.cpp b/qml/viewonlyimport.cpp\nindex 4dbb3041d2..145f14baa5 100644\n--- a/qml/viewonlyimport.cpp\n+++ b/qml/viewonlyimport.cpp\n@@ -220,9 +220,12 @@ ViewOnlyImport ParseJson(const std::string& text)\n             if (!request.label.empty() && (check.ranged || multipath || request.internal.value_or(false))) {\n                 return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a label, but only a single receive address can have one.\").arg(position));\n             }\n+            // Without a range, the wallet's keypool size bounds it, which isn't known here.\n+            if (request.next_index && !request.range) {\n+                return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index but no range.\").arg(position));\n+            }\n             if (check.ranged && request.next_index) {\n-                const int64_t first{request.range ? request.range->first : 0};\n-                if (*request.next_index < first || (request.range && *request.next_index > request.range->second)) {\n+                if (*request.next_index < request.range->first || *request.next_index > request.range->second) {\n                     return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index outside its range.\").arg(position));\n                 }\n             }\n@@ -321,6 +324,8 @@ const std::array KNOWN_KEY_VERSIONS{\n // [fingerprint/path]key, the key origin form wallets export.\n const QRegularExpression KEY_ORIGIN{QStringLiteral(R\"(^\\[([0-9a-fA-F]{8})((?:/[0-9]+['hH]?)*)\\]([1-9A-HJ-NP-Za-km-z]+)$)\")};\n const QRegularExpression ORIGIN_PURPOSE{QStringLiteral(R\"(^/(44|49|84|86)['hH])\")};\n+// BIP45 and BIP48 are multisig cosigner paths.\n+const QRegularExpression MULTISIG_PURPOSE{QStringLiteral(R\"(^/(45|48)['hH])\")};\n \n struct ExtendedKey {\n     bool recognized{false};\n@@ -394,6 +399,9 @@ ViewOnlyImport ParseExtendedKey(const ExtendedKey& key, const QString& origin, c\n {\n     using Kind = ViewOnlyImport::Kind;\n     if (!key.error.isEmpty()) return Failed(Kind::ExtendedKey, key.error);\n+    if (MULTISIG_PURPOSE.match(path).hasMatch()) {\n+        return Failed(Kind::ExtendedKey, QObject::tr(\"This key is from a multisig wallet. Only single-key wallets can be imported.\"));\n+    }\n     // The key's prefix wins, then a BIP44, 49, 84 or 86 path.\n     const std::optional<OutputType> path_type{PurposeType(path)};\n     std::optional<OutputType> type{key.type ? key.type : path_type};\n@@ -476,8 +484,10 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n             active_slots[{type, request.internal.value_or(false)}] = i;\n         }\n     }\n-    std::vector<bool> active(parsed.requests.size(), false);\n-    for (const auto& [slot, index] : active_slots) active[index] = true;\n+    const auto branch_active = [&](size_t i, bool change) {\n+        const auto slot{active_slots.find({parsed.sources[i].type, change})};\n+        return slot != active_slots.end() && slot->second == i;\n+    };\n     QString warning{parsed.warning};\n     if (warning.isEmpty() && std::ranges::none_of(active_slots, [](const auto& slot) { return slot.first.second; })) {\n         bool watches_change{false};\n@@ -489,7 +499,7 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n             : QObject::tr(\"Nothing here is for change addresses. Payments to the other wallet's change won't show, and this wallet can't prepare a transaction that needs change.\");\n     }\n \n-    // Receive and change of one key share a row.\n+    // Receive and change of one key share a row, unless only one of them stays active.\n     QVariantList rows;\n     QStringList row_keys;\n     for (size_t i = 0; i < parsed.requests.size(); ++i) {\n@@ -501,34 +511,36 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n         if (time) created = std::min(created.value_or(*time), *time);\n \n         const QString type{QmlUtil::OutputTypeLabel(source.type)};\n-        auto row_it{rows.begin()};\n-        for (; row_it != rows.end(); ++row_it) {\n-            const QVariantMap map{row_it->toMap()};\n-            if (map.value(QStringLiteral(\"addressType\")) == type && row_keys[std::distance(rows.begin(), row_it)] == source.key_id &&\n-                map.value(QStringLiteral(\"active\")) == bool(active[i]) && map.value(QStringLiteral(\"ranged\")) == source.ranged) {\n-                break;\n+        const std::vector<bool> branches{source.multipath ? std::vector<bool>{false, true} : std::vector<bool>{request.internal.value_or(false)}};\n+        for (const bool change : branches) {\n+            const bool active{branch_active(i, change)};\n+            auto row_it{rows.begin()};\n+            for (; row_it != rows.end(); ++row_it) {\n+                const QVariantMap map{row_it->toMap()};\n+                if (map.value(QStringLiteral(\"addressType\")) == type && row_keys[std::distance(rows.begin(), row_it)] == source.key_id &&\n+                    map.value(QStringLiteral(\"active\")) == active && map.value(QStringLiteral(\"ranged\")) == source.ranged) {\n+                    break;\n+                }\n             }\n+            if (row_it == rows.end()) {\n+                row_keys.append(source.key_id);\n+                rows.append(QVariantMap{{QStringLiteral(\"addressType\"), type},\n+                                        {QStringLiteral(\"key\"), source.key},\n+                                        {QStringLiteral(\"receive\"), false},\n+                                        {QStringLiteral(\"change\"), false},\n+                                        {QStringLiteral(\"active\"), active},\n+                                        {QStringLiteral(\"ranged\"), source.ranged},\n+                                        {QStringLiteral(\"createdTime\"), qlonglong(-1)}});\n+                row_it = std::prev(rows.end());\n+            }\n+            QVariantMap row{row_it->toMap()};\n+            row.insert(change ? QStringLiteral(\"change\") : QStringLiteral(\"receive\"), true);\n+            if (time) {\n+                const qlonglong row_time{row.value(QStringLiteral(\"createdTime\")).toLongLong()};\n+                row.insert(QStringLiteral(\"createdTime\"), row_time < 0 ? qlonglong(*time) : std::min(row_time, qlonglong(*time)));\n+            }\n+            *row_it = row;\n         }\n-        if (row_it == rows.end()) {\n-            row_keys.append(source.key_id);\n-            rows.append(QVariantMap{{QStringLiteral(\"addressType\"), type},\n-                                    {QStringLiteral(\"key\"), source.key},\n-                                    {QStringLiteral(\"receive\"), false},\n-                                    {QStringLiteral(\"change\"), false},\n-                                    {QStringLiteral(\"active\"), bool(active[i])},\n-                                    {QStringLiteral(\"ranged\"), source.ranged},\n-                                    {QStringLiteral(\"createdTime\"), qlonglong(-1)}});\n-            row_it = std::prev(rows.end());\n-        }\n-        QVariantMap row{row_it->toMap()};\n-        const bool change{request.internal.value_or(false)};\n-        if (source.multipath || !change) row.insert(QStringLiteral(\"receive\"), true);\n-        if (source.multipath || change) row.insert(QStringLiteral(\"change\"), true);\n-        if (time) {\n-            const qlonglong row_time{row.value(QStringLiteral(\"createdTime\")).toLongLong()};\n-            row.insert(QStringLiteral(\"createdTime\"), row_time < 0 ? qlonglong(*time) : std::min(row_time, qlonglong(*time)));\n-        }\n-        *row_it = row;\n     }\n     QStringList descriptors;\n     for (const ImportDescriptorRequest& request : parsed.requests) descriptors.append(QString::fromStdString(request.descriptor));\n@@ -552,3 +564,13 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n     }\n     return result;\n }\n+\n+int64_t ResolveImportTimes(std::vector<ImportDescriptorRequest>& requests, int64_t now)\n+{\n+    int64_t oldest{now};\n+    for (ImportDescriptorRequest& request : requests) {\n+        request.timestamp = request.timestamp.value_or(now);\n+        oldest = std::min(oldest, *request.timestamp);\n+    }\n+    return oldest;\n+}\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 442,
    "evidence_id": "8606513bfc124045aade5321655cc57f",
    "finding_id": "finding:8",
    "kind": "new_source",
    "line": 293,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/viewonlyimport.cpp",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "    //! Testnet, signet and regtest share these.\n    bool test;\n    bool is_private;\n    bool multisig;\n    std::optional<OutputType> type;\n};\n\n// BIP32 and SLIP-132 versions. The prefix of a ypub or zpub names its script type.\nconst std::array KNOWN_KEY_VERSIONS{\n    KnownKeyVersion{{0x04, 0x88, 0xb2, 0x1e}, false, false, false, std::nullopt},             // xpub\n    KnownKeyVersion{{0x04, 0x9d, 0x7c, 0xb2}, false, false, false, OutputType::P2SH_SEGWIT},  // ypub\n    KnownKeyVersion{{0x04, 0xb2, 0x47, 0x46}, false, false, false, OutputType::BECH32},       // zpub\n    KnownKeyVersion{{0x02, 0x95, 0xb4, 0x3f}, false, false, true, std::nullopt},              // Ypub\n    KnownKeyVersion{{0x02, 0xaa, 0x7e, 0xd3}, false, false, true, std::nullopt},              // Zpub\n    KnownKeyVersion{{0x04, 0x35, 0x87, 0xcf}, true, false, false, std::nullopt},              // tpub\n    KnownKeyVersion{{0x04, 0x4a, 0x52, 0x62}, true, false, false, OutputType::P2SH_SEGWIT},   // upub\n    KnownKeyVersion{{0x04, 0x5f, 0x1c, 0xf6}, true, false, false, OutputType::BECH32},        // vpub\n    KnownKeyVersion{{0x02, 0x42, 0x89, 0xef}, true, false, true, std::nullopt},               // Upub\n    KnownKeyVersion{{0x02, 0x57, 0x54, 0x83}, true, false, true, std::nullopt},               // Vpub\n    KnownKeyVersion{{0x04, 0x88, 0xad, 0xe4}, false, true, false, std::nullopt},              // xprv\n    KnownKeyVersion{{0x04, 0x9d, 0x78, 0x78}, false, true, false, std::nullopt},              // yprv\n    KnownKeyVersion{{0x04, 0xb2, 0x43, 0x0c}, false, true, false, std::nullopt},              // zprv\n    KnownKeyVersion{{0x02, 0x95, 0xb0, 0x05}, false, true, true, std::nullopt},               // Yprv\n    KnownKeyVersion{{0x02, 0xaa, 0x7a, 0x99}, false, true, true, std::nullopt},               // Zprv\n    KnownKeyVersion{{0x04, 0x35, 0x83, 0x94}, true, true, false, std::nullopt},               // tprv\n    KnownKeyVersion{{0x04, 0x4a, 0x4e, 0x28}, true, true, false, std::nullopt},               // uprv\n    KnownKeyVersion{{0x04, 0x5f, 0x18, 0xbc}, true, true, false, std::nullopt},               // vprv\n    KnownKeyVersion{{0x02, 0x42, 0x85, 0xb5}, true, true, true, std::nullopt},                // Uprv\n    KnownKeyVersion{{0x02, 0x57, 0x50, 0x48}, true, true, true, std::nullopt},                // Vprv\n};\n\n// [fingerprint/path]key, the key origin form wallets export.\nconst QRegularExpression KEY_ORIGIN{QStringLiteral(R\"(^\\[([0-9a-fA-F]{8})((?:/[0-9]+['hH]?)*)\\]([1-9A-HJ-NP-Za-km-z]+)$)\")};\nconst QRegularExpression ORIGIN_PURPOSE{QStringLiteral(R\"(^/(44|49|84|86)['hH])\")};\n// BIP45 and BIP48 are multisig cosigner paths.\nconst QRegularExpression MULTISIG_PURPOSE{QStringLiteral(R\"(^/(45|48)['hH])\")};\n\nstruct ExtendedKey {\n    bool recognized{false};\n    QString error;\n    //! The key with this network's xpub or tpub version.\n    std::string key;\n    std::optional<OutputType> type;\n};\n\nExtendedKey ReadExtendedKey(const std::string& text)\n{\n    std::vector<unsigned char> data;\n    if (!DecodeBase58Check(text, data, BIP32_EXTKEY_WITH_VERSION_SIZE) || data.size() != BIP32_EXTKEY_WITH_VERSION_SIZE) return {};\n    const auto known{std::ranges::find_if(KNOWN_KEY_VERSIONS, [&](const KnownKeyVersion& known) {\n        return std::equal(known.version.begin(), known.version.end(), data.begin());\n    })};\n    if (known == KNOWN_KEY_VERSIONS.end()) return {};\n\n    ExtendedKey result;\n    result.recognized = true;\n    if (known->is_private) {\n        result.error = QObject::tr(\"This is a private key. Enter the extended public key instead.\");\n        return result;\n    }\n    if (known->multisig) {\n        result.error = QObject::tr(\"This key is from a multisig wallet. Only single-key wallets can be imported.\");\n        return result;\n    }\n    const std::vector<unsigned char>& prefix{Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY)};\n    const KeyVersion& mainnet{KNOWN_KEY_VERSIONS.front().version};\n    if (known->test == std::equal(mainnet.begin(), mainnet.end(), prefix.begin(), prefix.end())) {\n        result.error = QObject::tr(\"This key is for a different network.\");\n        return result;\n    }\n    std::copy(prefix.begin(), prefix.end(), data.begin());\n    result.key = EncodeBase58Check(data);\n    if (!DecodeExtPubKey(result.key).pubkey.IsValid()) {\n        result.error = QObject::tr(\"This extended public key is not valid.\");\n        return result;\n    }\n    result.type = known->type;\n    return result;\n}\n\nstd::optional<OutputType> PurposeType(const QString& path)\n{\n    const QRegularExpressionMatch match{ORIGIN_PURPOSE.match(path)};\n    if (!match.hasMatch()) return std::nullopt;\n    switch (match.captured(1).toInt()) {\n    case 44: return OutputType::LEGACY;\n    case 49: return OutputType::P2SH_SEGWIT;\n    case 84: return OutputType::BECH32;\n    case 86: return OutputType::BECH32M;\n    }\n    return std::nullopt;\n}\n\nQString WrapKey(OutputType type, const QString& key)\n{\n    switch (type) {\n    case OutputType::LEGACY: return QStringLiteral(\"pkh(%1)\").arg(key);\n    case OutputType::P2SH_SEGWIT: return QStringLiteral(\"sh(wpkh(%1))\").arg(key);\n    case OutputType::BECH32: return QStringLiteral(\"wpkh(%1)\").arg(key);\n    case OutputType::BECH32M: return QStringLiteral(\"tr(%1)\").arg(key);\n    case OutputType::UNKNOWN: break;\n    }\n    return {};\n}\n\nViewOnlyImport ParseExtendedKey(const ExtendedKey& key, const QString& origin, const QString& path, const QString& address_type)\n{\n    using Kind = ViewOnlyImport::Kind;\n    if (!key.error.isEmpty()) return Failed(Kind::ExtendedKey, key.error);\n    if (MULTISIG_PURPOSE.match(path).hasMatch()) {\n        return Failed(Kind::ExtendedKey, QObject::tr(\"This key is from a multisig wallet. Only single-key wallets can be imported.\"));\n    }\n    // The key's prefix wins, then a BIP44, 49, 84 or 86 path.\n    const std::optional<OutputType> path_type{PurposeType(path)};\n    std::optional<OutputType> type{key.type ? key.type : path_type};\n    const bool needs_address_type{!type};\n    if (!type && !address_type.isEmpty()) {\n        type = ParseOutputType(address_type.toStdString());\n        if (!type || *type == OutputType::UNKNOWN) return Failed(Kind::ExtendedKey, QObject::tr(\"Choose a valid address type.\"));\n    }\n    ViewOnlyImport result;\n    if (type) result = ParseLines({WrapKey(*type, origin + QString::fromStdString(key.key) + QStringLiteral(\"/<0;1>/*\"))});\n    result.kind = Kind::ExtendedKey;\n    result.needs_address_type = needs_address_type;\n    result.key_id = origin + QString::fromStdString(key.key);\n    if (key.type && path_type && *key.type != *path_type) {\n        //: %1 and %2 are address types, such as \"Bech32 (SegWit)\".\n        result.warning = QObject::tr(\"The key's prefix says %1, but its origin path says %2. It is imported as %1. Check the wallet it came from.\")\n                             .arg(QmlUtil::OutputTypeLabel(*key.type), QmlUtil::OutputTypeLabel(*path_type));\n    }\n    return result;\n}\n\n} // namespace\n\nViewOnlyImport ParseViewOnlyImport(const QString& text, const QString& address_type)\n{\n    const QString trimmed{text.trimmed()};\n    if (trimmed.isEmpty()) return {};\n\n    const QRegularExpressionMatch origin{KEY_ORIGIN.match(trimmed)};\n    const QString key_text{origin.hasMatch() ? origin.captured(3) : trimmed};\n    if (const ExtendedKey key{ReadExtendedKey(key_text.toStdString())}; key.recognized) {\n        const QString origin_text{origin.hasMatch() ? QStringLiteral(\"[%1%2]\").arg(origin.captured(1), origin.captured(2)) : QString{}};\n        return ParseExtendedKey(key, origin_text, origin.captured(2), address_type);\n    }\n    // Only a key fits after a key origin, so this is a mistyped key rather than JSON.\n    if (origin.hasMatch()) {\n        return Failed(ViewOnlyImport::Kind::ExtendedKey, QObject::tr(\"This extended public key is not valid.\"));\n    }",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1144Partially replaced multipath descriptors appear fully activeqml/viewonlyimport.cppaddressed
Assessment

Activity is computed per receive/change branch, and multipath rows are split by branch activity, so a replaced receive branch can be shown inactive while change remains active.

path_diff: qml/viewonlyimport.cpp; new_source: qml/viewonlyimport.cpp

[
  {
    "evidence_id": "4a46a1b9932c481caa92ad9423662f39",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/viewonlyimport.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/viewonlyimport.cpp b/qml/viewonlyimport.cpp\nindex 4dbb3041d2..145f14baa5 100644\n--- a/qml/viewonlyimport.cpp\n+++ b/qml/viewonlyimport.cpp\n@@ -220,9 +220,12 @@ ViewOnlyImport ParseJson(const std::string& text)\n             if (!request.label.empty() && (check.ranged || multipath || request.internal.value_or(false))) {\n                 return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a label, but only a single receive address can have one.\").arg(position));\n             }\n+            // Without a range, the wallet's keypool size bounds it, which isn't known here.\n+            if (request.next_index && !request.range) {\n+                return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index but no range.\").arg(position));\n+            }\n             if (check.ranged && request.next_index) {\n-                const int64_t first{request.range ? request.range->first : 0};\n-                if (*request.next_index < first || (request.range && *request.next_index > request.range->second)) {\n+                if (*request.next_index < request.range->first || *request.next_index > request.range->second) {\n                     return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index outside its range.\").arg(position));\n                 }\n             }\n@@ -321,6 +324,8 @@ const std::array KNOWN_KEY_VERSIONS{\n // [fingerprint/path]key, the key origin form wallets export.\n const QRegularExpression KEY_ORIGIN{QStringLiteral(R\"(^\\[([0-9a-fA-F]{8})((?:/[0-9]+['hH]?)*)\\]([1-9A-HJ-NP-Za-km-z]+)$)\")};\n const QRegularExpression ORIGIN_PURPOSE{QStringLiteral(R\"(^/(44|49|84|86)['hH])\")};\n+// BIP45 and BIP48 are multisig cosigner paths.\n+const QRegularExpression MULTISIG_PURPOSE{QStringLiteral(R\"(^/(45|48)['hH])\")};\n \n struct ExtendedKey {\n     bool recognized{false};\n@@ -394,6 +399,9 @@ ViewOnlyImport ParseExtendedKey(const ExtendedKey& key, const QString& origin, c\n {\n     using Kind = ViewOnlyImport::Kind;\n     if (!key.error.isEmpty()) return Failed(Kind::ExtendedKey, key.error);\n+    if (MULTISIG_PURPOSE.match(path).hasMatch()) {\n+        return Failed(Kind::ExtendedKey, QObject::tr(\"This key is from a multisig wallet. Only single-key wallets can be imported.\"));\n+    }\n     // The key's prefix wins, then a BIP44, 49, 84 or 86 path.\n     const std::optional<OutputType> path_type{PurposeType(path)};\n     std::optional<OutputType> type{key.type ? key.type : path_type};\n@@ -476,8 +484,10 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n             active_slots[{type, request.internal.value_or(false)}] = i;\n         }\n     }\n-    std::vector<bool> active(parsed.requests.size(), false);\n-    for (const auto& [slot, index] : active_slots) active[index] = true;\n+    const auto branch_active = [&](size_t i, bool change) {\n+        const auto slot{active_slots.find({parsed.sources[i].type, change})};\n+        return slot != active_slots.end() && slot->second == i;\n+    };\n     QString warning{parsed.warning};\n     if (warning.isEmpty() && std::ranges::none_of(active_slots, [](const auto& slot) { return slot.first.second; })) {\n         bool watches_change{false};\n@@ -489,7 +499,7 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n             : QObject::tr(\"Nothing here is for change addresses. Payments to the other wallet's change won't show, and this wallet can't prepare a transaction that needs change.\");\n     }\n \n-    // Receive and change of one key share a row.\n+    // Receive and change of one key share a row, unless only one of them stays active.\n     QVariantList rows;\n     QStringList row_keys;\n     for (size_t i = 0; i < parsed.requests.size(); ++i) {\n@@ -501,34 +511,36 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n         if (time) created = std::min(created.value_or(*time), *time);\n \n         const QString type{QmlUtil::OutputTypeLabel(source.type)};\n-        auto row_it{rows.begin()};\n-        for (; row_it != rows.end(); ++row_it) {\n-            const QVariantMap map{row_it->toMap()};\n-            if (map.value(QStringLiteral(\"addressType\")) == type && row_keys[std::distance(rows.begin(), row_it)] == source.key_id &&\n-                map.value(QStringLiteral(\"active\")) == bool(active[i]) && map.value(QStringLiteral(\"ranged\")) == source.ranged) {\n-                break;\n+        const std::vector<bool> branches{source.multipath ? std::vector<bool>{false, true} : std::vector<bool>{request.internal.value_or(false)}};\n+        for (const bool change : branches) {\n+            const bool active{branch_active(i, change)};\n+            auto row_it{rows.begin()};\n+            for (; row_it != rows.end(); ++row_it) {\n+                const QVariantMap map{row_it->toMap()};\n+                if (map.value(QStringLiteral(\"addressType\")) == type && row_keys[std::distance(rows.begin(), row_it)] == source.key_id &&\n+                    map.value(QStringLiteral(\"active\")) == active && map.value(QStringLiteral(\"ranged\")) == source.ranged) {\n+                    break;\n+                }\n             }\n+            if (row_it == rows.end()) {\n+                row_keys.append(source.key_id);\n+                rows.append(QVariantMap{{QStringLiteral(\"addressType\"), type},\n+                                        {QStringLiteral(\"key\"), source.key},\n+                                        {QStringLiteral(\"receive\"), false},\n+                                        {QStringLiteral(\"change\"), false},\n+                                        {QStringLiteral(\"active\"), active},\n+                                        {QStringLiteral(\"ranged\"), source.ranged},\n+                                        {QStringLiteral(\"createdTime\"), qlonglong(-1)}});\n+                row_it = std::prev(rows.end());\n+            }\n+            QVariantMap row{row_it->toMap()};\n+            row.insert(change ? QStringLiteral(\"change\") : QStringLiteral(\"receive\"), true);\n+            if (time) {\n+                const qlonglong row_time{row.value(QStringLiteral(\"createdTime\")).toLongLong()};\n+                row.insert(QStringLiteral(\"createdTime\"), row_time < 0 ? qlonglong(*time) : std::min(row_time, qlonglong(*time)));\n+            }\n+            *row_it = row;\n         }\n-        if (row_it == rows.end()) {\n-            row_keys.append(source.key_id);\n-            rows.append(QVariantMap{{QStringLiteral(\"addressType\"), type},\n-                                    {QStringLiteral(\"key\"), source.key},\n-                                    {QStringLiteral(\"receive\"), false},\n-                                    {QStringLiteral(\"change\"), false},\n-                                    {QStringLiteral(\"active\"), bool(active[i])},\n-                                    {QStringLiteral(\"ranged\"), source.ranged},\n-                                    {QStringLiteral(\"createdTime\"), qlonglong(-1)}});\n-            row_it = std::prev(rows.end());\n-        }\n-        QVariantMap row{row_it->toMap()};\n-        const bool change{request.internal.value_or(false)};\n-        if (source.multipath || !change) row.insert(QStringLiteral(\"receive\"), true);\n-        if (source.multipath || change) row.insert(QStringLiteral(\"change\"), true);\n-        if (time) {\n-            const qlonglong row_time{row.value(QStringLiteral(\"createdTime\")).toLongLong()};\n-            row.insert(QStringLiteral(\"createdTime\"), row_time < 0 ? qlonglong(*time) : std::min(row_time, qlonglong(*time)));\n-        }\n-        *row_it = row;\n     }\n     QStringList descriptors;\n     for (const ImportDescriptorRequest& request : parsed.requests) descriptors.append(QString::fromStdString(request.descriptor));\n@@ -552,3 +564,13 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n     }\n     return result;\n }\n+\n+int64_t ResolveImportTimes(std::vector<ImportDescriptorRequest>& requests, int64_t now)\n+{\n+    int64_t oldest{now};\n+    for (ImportDescriptorRequest& request : requests) {\n+        request.timestamp = request.timestamp.value_or(now);\n+        oldest = std::min(oldest, *request.timestamp);\n+    }\n+    return oldest;\n+}\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 576,
    "evidence_id": "09acc135362c4bd5b4f792ab132d642c",
    "finding_id": "finding:7",
    "kind": "new_source",
    "line": 450,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/viewonlyimport.cpp",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "{\n    using Kind = ViewOnlyImport::Kind;\n    const ViewOnlyImport parsed{ParseViewOnlyImport(text, address_type)};\n    QVariantMap result;\n    if (parsed.kind == Kind::Empty) {\n        result.insert(QStringLiteral(\"status\"), QStringLiteral(\"empty\"));\n        return result;\n    }\n    const QString kind{parsed.kind == Kind::ExtendedKey ? QStringLiteral(\"extendedKey\")\n                       : parsed.kind == Kind::Descriptors ? QStringLiteral(\"descriptors\")\n                       : QStringLiteral(\"descriptorJson\")};\n    result.insert(QStringLiteral(\"kind\"), kind);\n    if (!parsed.error.isEmpty()) {\n        result.insert(QStringLiteral(\"status\"), QStringLiteral(\"invalid\"));\n        result.insert(QStringLiteral(\"error\"), parsed.error);\n        result.insert(QStringLiteral(\"errorLine\"), parsed.error_line);\n        return result;\n    }\n\n    QStringList address_types;\n    for (const OutputType type : parsed.output_types) address_types.append(QmlUtil::OutputTypeLabel(type));\n    const int64_t now{QDateTime::currentSecsSinceEpoch()};\n    std::optional<int64_t> created;\n    // An address type has one active receive and one active change descriptor.\n    // The wallet activates requests in order, so a later one replaces an earlier one.\n    std::map<std::pair<OutputType, bool>, size_t> active_slots;\n    for (size_t i = 0; i < parsed.requests.size(); ++i) {\n        const ImportDescriptorRequest& request{parsed.requests[i]};\n        if (!request.active) continue;\n        const OutputType type{parsed.sources[i].type};\n        if (parsed.sources[i].multipath) {\n            active_slots[{type, false}] = i;\n            active_slots[{type, true}] = i;\n        } else {\n            active_slots[{type, request.internal.value_or(false)}] = i;\n        }\n    }\n    const auto branch_active = [&](size_t i, bool change) {\n        const auto slot{active_slots.find({parsed.sources[i].type, change})};\n        return slot != active_slots.end() && slot->second == i;\n    };\n    QString warning{parsed.warning};\n    if (warning.isEmpty() && std::ranges::none_of(active_slots, [](const auto& slot) { return slot.first.second; })) {\n        bool watches_change{false};\n        for (size_t i = 0; i < parsed.requests.size(); ++i) {\n            watches_change |= parsed.sources[i].multipath || parsed.requests[i].internal.value_or(false);\n        }\n        warning = watches_change\n            ? QObject::tr(\"No change descriptor is active, so this wallet can't prepare a transaction that needs change.\")\n            : QObject::tr(\"Nothing here is for change addresses. Payments to the other wallet's change won't show, and this wallet can't prepare a transaction that needs change.\");\n    }\n\n    // Receive and change of one key share a row, unless only one of them stays active.\n    QVariantList rows;\n    QStringList row_keys;\n    for (size_t i = 0; i < parsed.requests.size(); ++i) {\n        const ImportDescriptorRequest& request{parsed.requests[i]};\n        const ViewOnlyImport::Source& source{parsed.sources[i]};\n        std::optional<int64_t> time;\n        // An unset timestamp here was \"now\".\n        if (std::ranges::find(parsed.undated, i) == parsed.undated.end()) time = request.timestamp.value_or(now);\n        if (time) created = std::min(created.value_or(*time), *time);\n\n        const QString type{QmlUtil::OutputTypeLabel(source.type)};\n        const std::vector<bool> branches{source.multipath ? std::vector<bool>{false, true} : std::vector<bool>{request.internal.value_or(false)}};\n        for (const bool change : branches) {\n            const bool active{branch_active(i, change)};\n            auto row_it{rows.begin()};\n            for (; row_it != rows.end(); ++row_it) {\n                const QVariantMap map{row_it->toMap()};\n                if (map.value(QStringLiteral(\"addressType\")) == type && row_keys[std::distance(rows.begin(), row_it)] == source.key_id &&\n                    map.value(QStringLiteral(\"active\")) == active && map.value(QStringLiteral(\"ranged\")) == source.ranged) {\n                    break;\n                }\n            }\n            if (row_it == rows.end()) {\n                row_keys.append(source.key_id);\n                rows.append(QVariantMap{{QStringLiteral(\"addressType\"), type},\n                                        {QStringLiteral(\"key\"), source.key},\n                                        {QStringLiteral(\"receive\"), false},\n                                        {QStringLiteral(\"change\"), false},\n                                        {QStringLiteral(\"active\"), active},\n                                        {QStringLiteral(\"ranged\"), source.ranged},\n                                        {QStringLiteral(\"createdTime\"), qlonglong(-1)}});\n                row_it = std::prev(rows.end());\n            }\n            QVariantMap row{row_it->toMap()};\n            row.insert(change ? QStringLiteral(\"change\") : QStringLiteral(\"receive\"), true);\n            if (time) {\n                const qlonglong row_time{row.value(QStringLiteral(\"createdTime\")).toLongLong()};\n                row.insert(QStringLiteral(\"createdTime\"), row_time < 0 ? qlonglong(*time) : std::min(row_time, qlonglong(*time)));\n            }\n            *row_it = row;\n        }\n    }\n    QStringList descriptors;\n    for (const ImportDescriptorRequest& request : parsed.requests) descriptors.append(QString::fromStdString(request.descriptor));\n    result.insert(QStringLiteral(\"importId\"), parsed.kind == Kind::ExtendedKey ? parsed.key_id : descriptors.join(QLatin1Char('\\n')));\n    result.insert(QStringLiteral(\"status\"), QStringLiteral(\"valid\"));\n    result.insert(QStringLiteral(\"descriptorCount\"), qulonglong(parsed.descriptor_count));\n    result.insert(QStringLiteral(\"addressTypes\"), address_types);\n    // A key waiting for its address type has no date either.\n    result.insert(QStringLiteral(\"needsBirthDate\"), !parsed.undated.empty() || (parsed.needs_address_type && parsed.requests.empty()));\n    result.insert(QStringLiteral(\"createdTime\"), qlonglong(created.value_or(-1)));\n    result.insert(QStringLiteral(\"needsAddressType\"), parsed.needs_address_type);\n    result.insert(QStringLiteral(\"warning\"), warning);\n    result.insert(QStringLiteral(\"rows\"), rows);\n    if (parsed.needs_address_type) {\n        QVariantList options;\n        for (const OutputType type : {OutputType::BECH32, OutputType::BECH32M, OutputType::P2SH_SEGWIT, OutputType::LEGACY}) {\n            options.append(QVariantMap{{QStringLiteral(\"id\"), QString::fromStdString(FormatOutputType(type))},\n                                       {QStringLiteral(\"label\"), QmlUtil::OutputTypeLabel(type)}});\n        }\n        result.insert(QStringLiteral(\"addressTypeOptions\"), options);\n    }\n    return result;\n}\n\nint64_t ResolveImportTimes(std::vector<ImportDescriptorRequest>& requests, int64_t now)\n{\n    int64_t oldest{now};\n    for (ImportDescriptorRequest& request : requests) {\n        request.timestamp = request.timestamp.value_or(now);\n        oldest = std::min(oldest, *request.timestamp);\n    }\n    return oldest;\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1144Same-named wallets share a recovery marker across directoriesqml/walletqmlcontroller.cppaddressed
Assessment

The pending marker is now keyed by the canonical wallet path rather than the wallet name, separating same-named wallets in different directories.

path_diff: qml/walletqmlcontroller.cpp; new_source: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "e38d939183c947c99f6fc7e3b286dff5",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 452a87cf64..81317bf10e 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -13,6 +13,7 @@\n #include <common/args.h>\n #include <common/settings.h>\n #include <interfaces/chain.h>\n+#include <interfaces/handler.h>\n #include <interfaces/node.h>\n #include <interfaces/wallet.h>\n #include <support/allocators/secure.h>\n@@ -45,6 +46,7 @@\n #include <QMetaObject>\n #include <QPointer>\n #include <QRegularExpression>\n+#include <QScopeGuard>\n #include <QSettings>\n #include <QStringList>\n #include <QTimer>\n@@ -122,48 +124,94 @@ void DiscardCreatedWallet(interfaces::WalletLoader& loader, std::unique_ptr<inte\n \n // A view-only import saves its descriptors before it rescans. The wallet's\n // best block is already the tip then, so after a crash it would load without\n-// the older transactions. This records where the rescan starts until it ends.\n-QString PendingImportKey(const std::string& wallet_name)\n+// the older transactions. This records where the rescan starts until it ends,\n+// and whether every descriptor was saved.\n+struct PendingImport {\n+    int64_t start{0};\n+    bool installed{false};\n+};\n+\n+// The marker belongs to the wallet file, not to its name.\n+std::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n {\n-    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_name).toHex()));\n+    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n+    std::error_code error;\n+    const fs::path canonical{fs::weakly_canonical(path, error)};\n+    return fs::PathToString(error ? path : canonical);\n }\n \n-void SetPendingImport(const std::string& wallet_name, std::optional<int64_t> time)\n+QString PendingImportKey(const std::string& wallet_path)\n+{\n+    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n+}\n+\n+void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n-    if (time) {\n-        settings.setValue(PendingImportKey(wallet_name), qlonglong(*time));\n-    } else {\n-        settings.remove(PendingImportKey(wallet_name));\n+    const QString key{PendingImportKey(wallet_path)};\n+    settings.remove(key);\n+    if (pending) {\n+        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n+        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n }\n \n-std::optional<int64_t> PendingImport(const std::string& wallet_name)\n+std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n {\n-    const QVariant time{QSettings{}.value(PendingImportKey(wallet_name))};\n-    return time.isValid() ? std::optional<int64_t>{time.toLongLong()} : std::nullopt;\n+    QSettings settings;\n+    const QString key{PendingImportKey(wallet_path)};\n+    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n+    if (!start.isValid()) return std::nullopt;\n+    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n+}\n+\n+// What the wallet takes as now for an import: the median time of the tip.\n+int64_t ChainNow(interfaces::WalletLoader& loader)\n+{\n+    wallet::WalletContext* context{loader.context()};\n+    int64_t time{0};\n+    if (context && context->chain) {\n+        interfaces::Chain& chain{*context->chain};\n+        if (const std::optional<int> height{chain.getHeight()};\n+            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n+            return time;\n+        }\n+    }\n+    return QDateTime::currentSecsSinceEpoch();\n }\n \n-bool ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control)\n+ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                const std::function<void(int)>& progress)\n {\n+    using Status = ImportRescanResult::Status;\n     wallet::WalletContext* context{node.walletLoader().context()};\n     const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n-    if (!wallet) return false;\n+    if (!wallet) return {Status::Stopped};\n     wallet::WalletRescanReserver reserver{*wallet};\n-    if (!reserver.reserve()) return false;\n-    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return false;\n+    // Another rescan of this wallet is running.\n+    if (!reserver.reserve()) return {Status::Failed};\n+    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n+    // The abort refers to this frame, and Scan can throw.\n+    const auto detach{qScopeGuard([&control] { control.detach(); })};\n+    const auto progress_handler{interfaces::MakeSignalHandler(\n+        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n     int start_height{0};\n     uint256 start_block;\n-    bool done{!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n-                                                               interfaces::FoundBlock().hash(start_block).height(start_height))};\n-    if (!done) {\n-        // Progress is saved, so a later load continues from where this stopped too.\n-        done = wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true).status ==\n-               wallet::ScanResult::SUCCESS;\n+    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n+                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n+        return {Status::Done};\n+    }\n+    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n+    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n+    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n+    ImportRescanResult stopped{Status::Stopped};\n+    int64_t last_time{0};\n+    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n+        stopped.checkpoint = last_time;\n     }\n-    control.detach();\n-    return done;\n+    return stopped;\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -214,8 +262,9 @@ WalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent\n     , m_open_local_path_fn([](const QString& path) {\n         return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n     })\n-    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control) {\n-        return ResumeImport(node, wallet_name, time, control);\n+    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                 const std::function<void(int)>& progress) {\n+        return ResumeImport(node, wallet_name, time, control, progress);\n     })\n {\n     m_empty_wallet->setNode(&m_node);\n@@ -524,8 +573,15 @@ void WalletQmlController::registerWalletModel(WalletQmlModel* wallet_model)\n void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n {\n     const QString name{wallet_model->name()};\n-    const std::optional<int64_t> time{PendingImport(name.toStdString())};\n-    if (!time) return;\n+    if (m_import_rescans.contains(name)) return;\n+    const std::string path{WalletPath(m_node.walletLoader(), name.toStdString())};\n+    const std::optional<PendingImport> pending{ReadPendingImport(path)};\n+    if (!pending) return;\n+    // Rescanning can't add the descriptors that were never saved.\n+    if (!pending->installed) {\n+        wallet_model->setHistoryRecovery(QStringLiteral(\"incomplete\"));\n+        return;\n+    }\n     if (!m_import_rescan_executor) {\n         m_import_rescan_executor = std::make_unique<BackendExecutor>();\n         m_import_rescan_executor->setObjectName(QStringLiteral(\"wallet-import-rescan\"));\n@@ -537,15 +593,43 @@ void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n     }\n     auto control{std::make_shared<RescanControl>()};\n     m_import_rescans[name] = control;\n-    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), time = *time, control] {\n-        // Stays pending when the rescan stops early, so the next load tries again.\n-        if (resume(name, time, *control)) SetPendingImport(name, std::nullopt);\n-    }, [this, name, control] {\n+    wallet_model->setHistoryRecovery(QStringLiteral(\"running\"));\n+    const QPointer<WalletQmlModel> model{wallet_model};\n+    auto progress = [bridge = m_notification_bridge, model](int percent) {\n+        QMetaObject::invokeMethod(bridge.get(), [model, percent] {\n+            if (model) model->setHistoryRecovery(QStringLiteral(\"running\"), percent < 100 ? percent : -1);\n+        }, Qt::QueuedConnection);\n+    };\n+    const auto finished = [this, name, control, model](bool failed) {\n         const auto it{m_import_rescans.find(name)};\n         if (it != m_import_rescans.end() && it->second == control) m_import_rescans.erase(it);\n+        if (model) model->setHistoryRecovery(failed ? QStringLiteral(\"failed\") : QString{});\n+    };\n+    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), path, start = pending->start,\n+                                            control, progress = std::move(progress)] {\n+        using Status = ImportRescanResult::Status;\n+        const ImportRescanResult result{resume(name, start, *control, progress)};\n+        if (result.status == Status::Done) {\n+            SetPendingImport(path, std::nullopt);\n+        } else if (result.status == Status::Stopped && result.checkpoint && *result.checkpoint > start) {\n+            // The next rescan starts a window before the last block read.\n+            SetPendingImport(path, PendingImport{*result.checkpoint, /*installed=*/true});\n+        }\n+        // The marker stays otherwise, so the next load tries again.\n+        return result.status;\n+    }, [finished](ImportRescanResult::Status status) {\n+        finished(status != ImportRescanResult::Status::Done);\n+    }, [finished](std::exception_ptr) {\n+        finished(/*failed=*/true);\n     });\n }\n \n+void WalletQmlController::retryHistoryRecovery(WalletQmlModel* wallet)\n+{\n+    if (!wallet || m_shutting_down || wallet->historyRecovery() != QStringLiteral(\"failed\")) return;\n+    resumeInterruptedImport(wallet);\n+}\n+\n void WalletQmlController::removeWalletModel(WalletQmlModel* wallet_model, bool remove)\n {\n     if (!wallet_model || wallet_model == m_empty_wallet) {\n@@ -676,9 +760,11 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             const auto error = util::ErrorString(wallet);\n             out.error = QString::fromStdString(error.translated.empty() ? error.original : error.translated);\n             if (out.error.isEmpty()) out.error = tr(\"Wallet creation failed.\");\n-        } else if (setup_wallet && !(out.error = setup_wallet(**wallet)).isEmpty()) {\n-            DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n-            SetPendingImport(wallet_name.toStdString(), std::nullopt);\n+        } else if (bool keep_wallet{false}; setup_wallet && !(out.error = setup_wallet(**wallet, keep_wallet)).isEmpty()) {\n+            if (!keep_wallet) {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }\n         } else {\n             out.wallet = std::move(*wallet);\n         }\n@@ -825,9 +911,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n     }\n     const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n-    // An unset timestamp means now.\n-    int64_t rescan_from{QDateTime::currentSecsSinceEpoch()};\n-    for (const auto& request : input.requests) rescan_from = std::min(rescan_from, request.timestamp.value_or(rescan_from));\n     std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n     auto control{std::make_shared<RescanControl>()};\n     m_import_control = control;\n@@ -837,14 +920,20 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                       creation_flags,\n                       WalletLoadAction::Create,\n                       /*report_create_error=*/false,\n-                      [node = &m_node, requests, rescan_from, control, guard = QPointer{this},\n-                       bridge = m_notification_bridge](interfaces::Wallet& wallet) mutable {\n+                      [node = &m_node, requests, control, guard = QPointer{this},\n+                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n-        SetPendingImport(wallet.getWalletName(), rescan_from);\n+        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n+        // Resolved here, so the marker starts where the wallet's rescan does.\n+        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n+        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n         std::vector<wallet::ImportResult> results;\n         {\n-            const auto progress{wallet.handleShowProgress([&wallet, control, guard, bridge](const std::string&, int percent) {\n+            // The rescan starts once every descriptor is saved.\n+            bool installed{false};\n+            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n+                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -856,12 +945,16 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         }\n         control->detach();\n         if (control->cancelled()) return cancelled;\n-        // Shutdown stops the rescan early without an error, which would keep a wallet missing history.\n-        if (node->shutdownRequested()) return WalletQmlController::tr(\"The import was interrupted before it found all transactions.\");\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n         }\n-        SetPendingImport(wallet.getWalletName(), std::nullopt);\n+        // Shutdown stops the rescan early without an error. The next start finishes it.\n+        if (node->shutdownRequested()) {\n+            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+            keep_wallet = true;\n+            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n+        }\n+        SetPendingImport(path, std::nullopt);\n         return QString{};\n     }, [node = &m_node, oldest_dated, chosen_date] {\n         // Checked before the wallet file exists, so another date can be tried with the same name.\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 247,
    "evidence_id": "d63990fddde742e9bb51abe31024c3df",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 98,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "    if (!chain.havePruned()) return false;\n    int height{0};\n    if (!oldest || !chain.findFirstBlockWithTimeAndHeight(*oldest - TIMESTAMP_WINDOW, 0, interfaces::FoundBlock().height(height))) {\n        return false;\n    }\n    const std::optional<int> prune_height{chain.getPruneHeight()};\n    return prune_height && height <= *prune_height;\n}\n\n// remove() only unloads the wallet. Its files are deleted too, so the name can be used again.\nvoid DiscardCreatedWallet(interfaces::WalletLoader& loader, std::unique_ptr<interfaces::Wallet> wallet)\n{\n    const std::string name{wallet->getWalletName()};\n    wallet::WalletContext* context{loader.context()};\n    std::shared_ptr<wallet::CWallet> shared{context ? wallet::GetWallet(*context, name) : nullptr};\n    wallet->remove();\n    wallet.reset();\n    if (!shared) return;\n    std::vector<fs::path> paths{shared->GetDatabase().Files()};\n    if (!name.empty() && !paths.empty()) paths.push_back(paths.front().parent_path());\n    // The database closes once the last reference is gone.\n    wallet::WaitForDeleteWallet(std::move(shared));\n    std::error_code error;\n    // A directory is only removed when empty.\n    for (const fs::path& path : paths) fs::remove(path, error);\n}\n\n// A view-only import saves its descriptors before it rescans. The wallet's\n// best block is already the tip then, so after a crash it would load without\n// the older transactions. This records where the rescan starts until it ends,\n// and whether every descriptor was saved.\nstruct PendingImport {\n    int64_t start{0};\n    bool installed{false};\n};\n\n// The marker belongs to the wallet file, not to its name.\nstd::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n{\n    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n    std::error_code error;\n    const fs::path canonical{fs::weakly_canonical(path, error)};\n    return fs::PathToString(error ? path : canonical);\n}\n\nQString PendingImportKey(const std::string& wallet_path)\n{\n    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n}\n\nvoid SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n{\n    QSettings settings;\n    const QString key{PendingImportKey(wallet_path)};\n    settings.remove(key);\n    if (pending) {\n        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n    }\n    settings.sync();\n}\n\nstd::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n{\n    QSettings settings;\n    const QString key{PendingImportKey(wallet_path)};\n    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n    if (!start.isValid()) return std::nullopt;\n    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n}\n\n// What the wallet takes as now for an import: the median time of the tip.\nint64_t ChainNow(interfaces::WalletLoader& loader)\n{\n    wallet::WalletContext* context{loader.context()};\n    int64_t time{0};\n    if (context && context->chain) {\n        interfaces::Chain& chain{*context->chain};\n        if (const std::optional<int> height{chain.getHeight()};\n            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n            return time;\n        }\n    }\n    return QDateTime::currentSecsSinceEpoch();\n}\n\nImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n                                const std::function<void(int)>& progress)\n{\n    using Status = ImportRescanResult::Status;\n    wallet::WalletContext* context{node.walletLoader().context()};\n    const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n    if (!wallet) return {Status::Stopped};\n    wallet::WalletRescanReserver reserver{*wallet};\n    // Another rescan of this wallet is running.\n    if (!reserver.reserve()) return {Status::Failed};\n    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n    // The abort refers to this frame, and Scan can throw.\n    const auto detach{qScopeGuard([&control] { control.detach(); })};\n    const auto progress_handler{interfaces::MakeSignalHandler(\n        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n    int start_height{0};\n    uint256 start_block;\n    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n        return {Status::Done};\n    }\n    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n    ImportRescanResult stopped{Status::Stopped};\n    int64_t last_time{0};\n    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n        stopped.checkpoint = last_time;\n    }\n    return stopped;\n}\n\nQString ImportErrorText(const wallet::ImportError& error)\n{\n    const bilingual_str& message{error.wallet_error.message};\n    return QString::fromStdString(message.translated.empty() ? message.original : message.translated);\n}\n} // namespace\n\nbool RescanControl::attach(std::function<void()> abort)\n{\n    const std::lock_guard lock{m_mutex};\n    if (m_cancelled) return false;\n    m_abort = std::move(abort);\n    return true;\n}\n\nvoid RescanControl::detach()\n{\n    const std::lock_guard lock{m_mutex};\n    m_abort = nullptr;\n}\n\nvoid RescanControl::cancel()\n{\n    const std::lock_guard lock{m_mutex};\n    m_cancelled = true;\n    if (m_abort) m_abort();\n}\n\nbool RescanControl::cancelled() const\n{\n    const std::lock_guard lock{m_mutex};",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1144Recovery uses wall-clock time for "now" importsqml/walletqmlcontroller.cppaddressed
Assessment

Recovery start times are resolved against the chain's tip median time before the marker is written. ResolveImportTimes assigns that value to unset request timestamps and returns the oldest resolved timestamp.

path_diff: qml/walletqmlcontroller.cpp; new_source: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "09eb40c8a26b42de86c58bc07694a24b",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 452a87cf64..81317bf10e 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -13,6 +13,7 @@\n #include <common/args.h>\n #include <common/settings.h>\n #include <interfaces/chain.h>\n+#include <interfaces/handler.h>\n #include <interfaces/node.h>\n #include <interfaces/wallet.h>\n #include <support/allocators/secure.h>\n@@ -45,6 +46,7 @@\n #include <QMetaObject>\n #include <QPointer>\n #include <QRegularExpression>\n+#include <QScopeGuard>\n #include <QSettings>\n #include <QStringList>\n #include <QTimer>\n@@ -122,48 +124,94 @@ void DiscardCreatedWallet(interfaces::WalletLoader& loader, std::unique_ptr<inte\n \n // A view-only import saves its descriptors before it rescans. The wallet's\n // best block is already the tip then, so after a crash it would load without\n-// the older transactions. This records where the rescan starts until it ends.\n-QString PendingImportKey(const std::string& wallet_name)\n+// the older transactions. This records where the rescan starts until it ends,\n+// and whether every descriptor was saved.\n+struct PendingImport {\n+    int64_t start{0};\n+    bool installed{false};\n+};\n+\n+// The marker belongs to the wallet file, not to its name.\n+std::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n {\n-    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_name).toHex()));\n+    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n+    std::error_code error;\n+    const fs::path canonical{fs::weakly_canonical(path, error)};\n+    return fs::PathToString(error ? path : canonical);\n }\n \n-void SetPendingImport(const std::string& wallet_name, std::optional<int64_t> time)\n+QString PendingImportKey(const std::string& wallet_path)\n+{\n+    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n+}\n+\n+void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n-    if (time) {\n-        settings.setValue(PendingImportKey(wallet_name), qlonglong(*time));\n-    } else {\n-        settings.remove(PendingImportKey(wallet_name));\n+    const QString key{PendingImportKey(wallet_path)};\n+    settings.remove(key);\n+    if (pending) {\n+        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n+        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n }\n \n-std::optional<int64_t> PendingImport(const std::string& wallet_name)\n+std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n {\n-    const QVariant time{QSettings{}.value(PendingImportKey(wallet_name))};\n-    return time.isValid() ? std::optional<int64_t>{time.toLongLong()} : std::nullopt;\n+    QSettings settings;\n+    const QString key{PendingImportKey(wallet_path)};\n+    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n+    if (!start.isValid()) return std::nullopt;\n+    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n+}\n+\n+// What the wallet takes as now for an import: the median time of the tip.\n+int64_t ChainNow(interfaces::WalletLoader& loader)\n+{\n+    wallet::WalletContext* context{loader.context()};\n+    int64_t time{0};\n+    if (context && context->chain) {\n+        interfaces::Chain& chain{*context->chain};\n+        if (const std::optional<int> height{chain.getHeight()};\n+            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n+            return time;\n+        }\n+    }\n+    return QDateTime::currentSecsSinceEpoch();\n }\n \n-bool ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control)\n+ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                const std::function<void(int)>& progress)\n {\n+    using Status = ImportRescanResult::Status;\n     wallet::WalletContext* context{node.walletLoader().context()};\n     const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n-    if (!wallet) return false;\n+    if (!wallet) return {Status::Stopped};\n     wallet::WalletRescanReserver reserver{*wallet};\n-    if (!reserver.reserve()) return false;\n-    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return false;\n+    // Another rescan of this wallet is running.\n+    if (!reserver.reserve()) return {Status::Failed};\n+    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n+    // The abort refers to this frame, and Scan can throw.\n+    const auto detach{qScopeGuard([&control] { control.detach(); })};\n+    const auto progress_handler{interfaces::MakeSignalHandler(\n+        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n     int start_height{0};\n     uint256 start_block;\n-    bool done{!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n-                                                               interfaces::FoundBlock().hash(start_block).height(start_height))};\n-    if (!done) {\n-        // Progress is saved, so a later load continues from where this stopped too.\n-        done = wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true).status ==\n-               wallet::ScanResult::SUCCESS;\n+    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n+                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n+        return {Status::Done};\n+    }\n+    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n+    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n+    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n+    ImportRescanResult stopped{Status::Stopped};\n+    int64_t last_time{0};\n+    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n+        stopped.checkpoint = last_time;\n     }\n-    control.detach();\n-    return done;\n+    return stopped;\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -214,8 +262,9 @@ WalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent\n     , m_open_local_path_fn([](const QString& path) {\n         return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n     })\n-    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control) {\n-        return ResumeImport(node, wallet_name, time, control);\n+    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                 const std::function<void(int)>& progress) {\n+        return ResumeImport(node, wallet_name, time, control, progress);\n     })\n {\n     m_empty_wallet->setNode(&m_node);\n@@ -524,8 +573,15 @@ void WalletQmlController::registerWalletModel(WalletQmlModel* wallet_model)\n void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n {\n     const QString name{wallet_model->name()};\n-    const std::optional<int64_t> time{PendingImport(name.toStdString())};\n-    if (!time) return;\n+    if (m_import_rescans.contains(name)) return;\n+    const std::string path{WalletPath(m_node.walletLoader(), name.toStdString())};\n+    const std::optional<PendingImport> pending{ReadPendingImport(path)};\n+    if (!pending) return;\n+    // Rescanning can't add the descriptors that were never saved.\n+    if (!pending->installed) {\n+        wallet_model->setHistoryRecovery(QStringLiteral(\"incomplete\"));\n+        return;\n+    }\n     if (!m_import_rescan_executor) {\n         m_import_rescan_executor = std::make_unique<BackendExecutor>();\n         m_import_rescan_executor->setObjectName(QStringLiteral(\"wallet-import-rescan\"));\n@@ -537,15 +593,43 @@ void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n     }\n     auto control{std::make_shared<RescanControl>()};\n     m_import_rescans[name] = control;\n-    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), time = *time, control] {\n-        // Stays pending when the rescan stops early, so the next load tries again.\n-        if (resume(name, time, *control)) SetPendingImport(name, std::nullopt);\n-    }, [this, name, control] {\n+    wallet_model->setHistoryRecovery(QStringLiteral(\"running\"));\n+    const QPointer<WalletQmlModel> model{wallet_model};\n+    auto progress = [bridge = m_notification_bridge, model](int percent) {\n+        QMetaObject::invokeMethod(bridge.get(), [model, percent] {\n+            if (model) model->setHistoryRecovery(QStringLiteral(\"running\"), percent < 100 ? percent : -1);\n+        }, Qt::QueuedConnection);\n+    };\n+    const auto finished = [this, name, control, model](bool failed) {\n         const auto it{m_import_rescans.find(name)};\n         if (it != m_import_rescans.end() && it->second == control) m_import_rescans.erase(it);\n+        if (model) model->setHistoryRecovery(failed ? QStringLiteral(\"failed\") : QString{});\n+    };\n+    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), path, start = pending->start,\n+                                            control, progress = std::move(progress)] {\n+        using Status = ImportRescanResult::Status;\n+        const ImportRescanResult result{resume(name, start, *control, progress)};\n+        if (result.status == Status::Done) {\n+            SetPendingImport(path, std::nullopt);\n+        } else if (result.status == Status::Stopped && result.checkpoint && *result.checkpoint > start) {\n+            // The next rescan starts a window before the last block read.\n+            SetPendingImport(path, PendingImport{*result.checkpoint, /*installed=*/true});\n+        }\n+        // The marker stays otherwise, so the next load tries again.\n+        return result.status;\n+    }, [finished](ImportRescanResult::Status status) {\n+        finished(status != ImportRescanResult::Status::Done);\n+    }, [finished](std::exception_ptr) {\n+        finished(/*failed=*/true);\n     });\n }\n \n+void WalletQmlController::retryHistoryRecovery(WalletQmlModel* wallet)\n+{\n+    if (!wallet || m_shutting_down || wallet->historyRecovery() != QStringLiteral(\"failed\")) return;\n+    resumeInterruptedImport(wallet);\n+}\n+\n void WalletQmlController::removeWalletModel(WalletQmlModel* wallet_model, bool remove)\n {\n     if (!wallet_model || wallet_model == m_empty_wallet) {\n@@ -676,9 +760,11 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             const auto error = util::ErrorString(wallet);\n             out.error = QString::fromStdString(error.translated.empty() ? error.original : error.translated);\n             if (out.error.isEmpty()) out.error = tr(\"Wallet creation failed.\");\n-        } else if (setup_wallet && !(out.error = setup_wallet(**wallet)).isEmpty()) {\n-            DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n-            SetPendingImport(wallet_name.toStdString(), std::nullopt);\n+        } else if (bool keep_wallet{false}; setup_wallet && !(out.error = setup_wallet(**wallet, keep_wallet)).isEmpty()) {\n+            if (!keep_wallet) {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }\n         } else {\n             out.wallet = std::move(*wallet);\n         }\n@@ -825,9 +911,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n     }\n     const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n-    // An unset timestamp means now.\n-    int64_t rescan_from{QDateTime::currentSecsSinceEpoch()};\n-    for (const auto& request : input.requests) rescan_from = std::min(rescan_from, request.timestamp.value_or(rescan_from));\n     std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n     auto control{std::make_shared<RescanControl>()};\n     m_import_control = control;\n@@ -837,14 +920,20 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                       creation_flags,\n                       WalletLoadAction::Create,\n                       /*report_create_error=*/false,\n-                      [node = &m_node, requests, rescan_from, control, guard = QPointer{this},\n-                       bridge = m_notification_bridge](interfaces::Wallet& wallet) mutable {\n+                      [node = &m_node, requests, control, guard = QPointer{this},\n+                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n-        SetPendingImport(wallet.getWalletName(), rescan_from);\n+        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n+        // Resolved here, so the marker starts where the wallet's rescan does.\n+        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n+        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n         std::vector<wallet::ImportResult> results;\n         {\n-            const auto progress{wallet.handleShowProgress([&wallet, control, guard, bridge](const std::string&, int percent) {\n+            // The rescan starts once every descriptor is saved.\n+            bool installed{false};\n+            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n+                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -856,12 +945,16 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         }\n         control->detach();\n         if (control->cancelled()) return cancelled;\n-        // Shutdown stops the rescan early without an error, which would keep a wallet missing history.\n-        if (node->shutdownRequested()) return WalletQmlController::tr(\"The import was interrupted before it found all transactions.\");\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n         }\n-        SetPendingImport(wallet.getWalletName(), std::nullopt);\n+        // Shutdown stops the rescan early without an error. The next start finishes it.\n+        if (node->shutdownRequested()) {\n+            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+            keep_wallet = true;\n+            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n+        }\n+        SetPendingImport(path, std::nullopt);\n         return QString{};\n     }, [node = &m_node, oldest_dated, chosen_date] {\n         // Checked before the wallet file exists, so another date can be tried with the same name.\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 948,
    "evidence_id": "a77af839b906440c80ae0897a1fba331",
    "finding_id": "finding:5",
    "kind": "new_source",
    "line": 799,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "    clearWalletMigrationStatus();\n    if (!m_initialized) {\n        setWalletCreateError(tr(\"Wallets are still loading. Try again in a moment.\"));\n        return;\n    }\n\n    const QString name_error = walletNameAvailabilityError(name);\n    if (!name_error.isEmpty()) {\n        setWalletCreateError(name_error);\n        return;\n    }\n\n    SecureString secure_passphrase{QmlUtil::SecureStringFromQString(passphrase)};\n    createWalletAsync(name.trimmed(),\n                      std::move(secure_passphrase),\n                      wallet::WALLET_FLAG_DESCRIPTORS,\n                      WalletLoadAction::Create,\n                      /*report_create_error=*/true);\n}\n\nbool WalletQmlController::createExternalSignerWallet(const QString& name)\n{\n    clearWalletLoadStatus();\n    clearWalletMigrationStatus();\n    if (!m_initialized) {\n        setWalletLoadError(tr(\"Wallets are still loading. Try again in a moment.\"));\n        return false;\n    }\n\n    const QString wallet_name = name.trimmed();\n    const QString name_error = walletNameAvailabilityError(wallet_name);\n    if (!name_error.isEmpty()) {\n        setWalletLoadError(name_error);\n        return false;\n    }\n\n    refreshExternalSignerStatus();\n    if (!m_external_signer_path_configured) {\n        setWalletLoadError(tr(\"Set an external signer path in Wallet settings first.\"));\n        return false;\n    }\n    if (!m_external_signer_error.isEmpty()) {\n        setWalletLoadError(m_external_signer_error);\n        return false;\n    }\n    if (m_external_signer_count == 0) {\n        setWalletLoadError(tr(\"Connect an external signer and try again.\"));\n        return false;\n    }\n    if (m_external_signer_count > 1) {\n        setWalletLoadError(tr(\"More than one external signer was found. Connect only one device and try again.\"));\n        return false;\n    }\n\n    constexpr uint64_t flags = wallet::WALLET_FLAG_DESCRIPTORS |\n        wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS |\n        wallet::WALLET_FLAG_EXTERNAL_SIGNER;\n    createWalletAsync(wallet_name,\n                      SecureString{},\n                      flags,\n                      WalletLoadAction::Load,\n                      /*report_create_error=*/false);\n    return true;\n}\n\nvoid WalletQmlController::createWatchOnlyWallet(const QString& name, const QString& import_text, qint64 birth_time,\n                                                const QString& address_type)\n{\n    if (m_wallet_load_in_progress) {\n        return;\n    }\n    clearWalletLoadStatus();\n    clearWalletMigrationStatus();\n    if (!m_initialized) {\n        setWalletLoadError(tr(\"Wallets are still loading. Try again in a moment.\"));\n        return;\n    }\n\n    ViewOnlyImport input{ParseViewOnlyImport(import_text, address_type)};\n    if (input.kind == ViewOnlyImport::Kind::Empty) {\n        setWalletLoadError(tr(\"Enter descriptors, or an extended public key (xpub).\"));\n        return;\n    }\n    if (!input.error.isEmpty()) {\n        setWalletLoadError(input.error);\n        return;\n    }\n    if (input.requests.empty()) {\n        setWalletLoadError(tr(\"Choose the address type of this key.\"));\n        return;\n    }\n    if (!input.undated.empty()) {\n        if (birth_time < 0) {\n            setWalletLoadError(tr(\"Choose when this wallet was created.\"));\n            return;\n        }\n        for (const size_t index : input.undated) input.requests[index].timestamp = birth_time;\n    }\n\n    const QString name_error = walletNameAvailabilityError(name);\n    if (!name_error.isEmpty()) {\n        setWalletLoadError(name_error);\n        return;\n    }\n\n    const uint64_t creation_flags = wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS |\n                                    wallet::WALLET_FLAG_DESCRIPTORS |\n                                    wallet::WALLET_FLAG_BLANK_WALLET;\n    // Only undated requests take the chosen date, so a dated one can need pruned blocks whatever the date.\n    std::optional<int64_t> oldest_dated;\n    for (size_t i = 0; i < input.requests.size(); ++i) {\n        const std::optional<int64_t>& time{input.requests[i].timestamp};\n        if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n    }\n    const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n    std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n    auto control{std::make_shared<RescanControl>()};\n    m_import_control = control;\n    setImportProgress(-1);\n    createWalletAsync(name.trimmed(),\n                      SecureString{},\n                      creation_flags,\n                      WalletLoadAction::Create,\n                      /*report_create_error=*/false,\n                      [node = &m_node, requests, control, guard = QPointer{this},\n                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n        const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n        if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n        // Resolved here, so the marker starts where the wallet's rescan does.\n        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n        std::vector<wallet::ImportResult> results;\n        {\n            // The rescan starts once every descriptor is saved.\n            bool installed{false};\n            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n                // Starting a rescan clears an earlier abort.\n                if (control->cancelled()) wallet.abortRescan();\n                QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n                    if (guard) guard->setImportProgress(percent < 100 ? percent : -1);\n                }, Qt::QueuedConnection);\n            })};\n            // Imports the descriptors, then rescans from the oldest timestamp.\n            results = wallet.importDescriptors(requests);\n        }\n        control->detach();\n        if (control->cancelled()) return cancelled;\n        for (const wallet::ImportResult& result : results) {",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1144Recovery has no visible pending or failed stateqml/walletqmlcontroller.cppaddressed
Assessment

Recovery is represented on the wallet model with running/failed states; scan progress is forwarded, and a retry method is provided for failed recovery. The new completion handling also exposes failure instead of silently leaving the wallet without status.

path_diff: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "5cdf0a9625d348eeb2e43d5abb4cd850",
    "finding_id": "finding:4",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 452a87cf64..08c013c361 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -13,6 +13,7 @@\n #include <common/args.h>\n #include <common/settings.h>\n #include <interfaces/chain.h>\n+#include <interfaces/handler.h>\n #include <interfaces/node.h>\n #include <interfaces/wallet.h>\n #include <support/allocators/secure.h>\n@@ -45,6 +46,7 @@\n #include <QMetaObject>\n #include <QPointer>\n #include <QRegularExpression>\n+#include <QScopeGuard>\n #include <QSettings>\n #include <QStringList>\n #include <QTimer>\n@@ -122,48 +124,92 @@ void DiscardCreatedWallet(interfaces::WalletLoader& loader, std::unique_ptr<inte\n \n // A view-only import saves its descriptors before it rescans. The wallet's\n // best block is already the tip then, so after a crash it would load without\n-// the older transactions. This records where the rescan starts until it ends.\n-QString PendingImportKey(const std::string& wallet_name)\n+// the older transactions. This records where the rescan starts until it ends,\n+// and whether every descriptor was saved.\n+struct PendingImport {\n+    int64_t start{0};\n+    bool installed{false};\n+};\n+\n+// The marker belongs to the wallet file, not to its name.\n+std::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n+{\n+    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n+    std::error_code error;\n+    const fs::path canonical{fs::weakly_canonical(path, error)};\n+    return fs::PathToString(error ? path : canonical);\n+}\n+\n+QString PendingImportKey(const std::string& wallet_path)\n {\n-    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_name).toHex()));\n+    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n }\n \n-void SetPendingImport(const std::string& wallet_name, std::optional<int64_t> time)\n+bool SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n-    if (time) {\n-        settings.setValue(PendingImportKey(wallet_name), qlonglong(*time));\n-    } else {\n-        settings.remove(PendingImportKey(wallet_name));\n+    const QString key{PendingImportKey(wallet_path)};\n+    settings.remove(key);\n+    if (pending) {\n+        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n+        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n+    return settings.status() == QSettings::NoError;\n }\n \n-std::optional<int64_t> PendingImport(const std::string& wallet_name)\n+std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n {\n-    const QVariant time{QSettings{}.value(PendingImportKey(wallet_name))};\n-    return time.isValid() ? std::optional<int64_t>{time.toLongLong()} : std::nullopt;\n+    QSettings settings;\n+    const QString key{PendingImportKey(wallet_path)};\n+    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n+    if (!start.isValid()) return std::nullopt;\n+    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n }\n \n-bool ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control)\n+// What the wallet takes as now for an import: the median time of the tip.\n+int64_t ChainNow(interfaces::WalletLoader& loader)\n {\n+    wallet::WalletContext* context{loader.context()};\n+    int64_t time{0};\n+    if (context && context->chain) {\n+        interfaces::Chain& chain{*context->chain};\n+        if (const std::optional<int> height{chain.getHeight()};\n+            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n+            return time;\n+        }\n+    }\n+    return QDateTime::currentSecsSinceEpoch();\n+}\n+\n+ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                const std::function<void(int)>& progress)\n+{\n+    using Status = ImportRescanResult::Status;\n     wallet::WalletContext* context{node.walletLoader().context()};\n     const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n-    if (!wallet) return false;\n+    if (!wallet) return {Status::Stopped};\n     wallet::WalletRescanReserver reserver{*wallet};\n-    if (!reserver.reserve()) return false;\n-    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return false;\n+    // Another rescan of this wallet is running.\n+    if (!reserver.reserve()) return {Status::Failed};\n+    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n+    // The abort refers to this frame, and Scan can throw.\n+    const auto detach{qScopeGuard([&control] { control.detach(); })};\n+    const auto progress_handler{interfaces::MakeSignalHandler(\n+        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n     int start_height{0};\n     uint256 start_block;\n-    bool done{!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n-                                                               interfaces::FoundBlock().hash(start_block).height(start_height))};\n-    if (!done) {\n-        // Progress is saved, so a later load continues from where this stopped too.\n-        done = wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true).status ==\n-               wallet::ScanResult::SUCCESS;\n+    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n+                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n+        return {Status::Done};\n     }\n-    control.detach();\n-    return done;\n+    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n+    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n+    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n+    int64_t last_time{0};\n+    const bool checkpoint{result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+                          wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))};\n+    return {Status::Stopped, checkpoint ? std::optional<int64_t>{last_time} : std::nullopt};\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -214,8 +260,9 @@ WalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent\n     , m_open_local_path_fn([](const QString& path) {\n         return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n     })\n-    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control) {\n-        return ResumeImport(node, wallet_name, time, control);\n+    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                 const std::function<void(int)>& progress) {\n+        return ResumeImport(node, wallet_name, time, control, progress);\n     })\n {\n     m_empty_wallet->setNode(&m_node);\n@@ -524,8 +571,15 @@ void WalletQmlController::registerWalletModel(WalletQmlModel* wallet_model)\n void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n {\n     const QString name{wallet_model->name()};\n-    const std::optional<int64_t> time{PendingImport(name.toStdString())};\n-    if (!time) return;\n+    if (m_import_rescans.contains(name)) return;\n+    const std::string path{WalletPath(m_node.walletLoader(), name.toStdString())};\n+    const std::optional<PendingImport> pending{ReadPendingImport(path)};\n+    if (!pending) return;\n+    // Rescanning can't add the descriptors that were never saved.\n+    if (!pending->installed) {\n+        wallet_model->setHistoryRecovery(QStringLiteral(\"incomplete\"));\n+        return;\n+    }\n     if (!m_import_rescan_executor) {\n         m_import_rescan_executor = std::make_unique<BackendExecutor>();\n         m_import_rescan_executor->setObjectName(QStringLiteral(\"wallet-import-rescan\"));\n@@ -537,15 +591,43 @@ void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n     }\n     auto control{std::make_shared<RescanControl>()};\n     m_import_rescans[name] = control;\n-    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), time = *time, control] {\n-        // Stays pending when the rescan stops early, so the next load tries again.\n-        if (resume(name, time, *control)) SetPendingImport(name, std::nullopt);\n-    }, [this, name, control] {\n+    wallet_model->setHistoryRecovery(QStringLiteral(\"running\"));\n+    const QPointer<WalletQmlModel> model{wallet_model};\n+    auto progress = [bridge = m_notification_bridge, model](int percent) {\n+        QMetaObject::invokeMethod(bridge.get(), [model, percent] {\n+            if (model) model->setHistoryRecovery(QStringLiteral(\"running\"), percent < 100 ? percent : -1);\n+        }, Qt::QueuedConnection);\n+    };\n+    const auto finished = [this, name, control, model](bool failed) {\n         const auto it{m_import_rescans.find(name)};\n         if (it != m_import_rescans.end() && it->second == control) m_import_rescans.erase(it);\n+        if (model) model->setHistoryRecovery(failed ? QStringLiteral(\"failed\") : QString{});\n+    };\n+    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), path, start = pending->start,\n+                                            control, progress = std::move(progress)] {\n+        using Status = ImportRescanResult::Status;\n+        const ImportRescanResult result{resume(name, start, *control, progress)};\n+        if (result.status == Status::Done) {\n+            SetPendingImport(path, std::nullopt);\n+        } else if (result.status == Status::Stopped && result.checkpoint && *result.checkpoint > start) {\n+            // The next rescan starts a window before the last block read.\n+            SetPendingImport(path, PendingImport{*result.checkpoint, /*installed=*/true});\n+        }\n+        // The marker stays otherwise, so the next load tries again.\n+        return result.status;\n+    }, [finished](ImportRescanResult::Status status) {\n+        finished(status != ImportRescanResult::Status::Done);\n+    }, [finished](std::exception_ptr) {\n+        finished(/*failed=*/true);\n     });\n }\n \n+void WalletQmlController::retryHistoryRecovery(WalletQmlModel* wallet)\n+{\n+    if (!wallet || m_shutting_down || wallet->historyRecovery() != QStringLiteral(\"failed\")) return;\n+    resumeInterruptedImport(wallet);\n+}\n+\n void WalletQmlController::removeWalletModel(WalletQmlModel* wallet_model, bool remove)\n {\n     if (!wallet_model || wallet_model == m_empty_wallet) {\n@@ -652,7 +734,8 @@ void WalletQmlController::createWalletAsync(const QString& name,\n                                             WalletLoadAction load_action,\n                                             bool report_create_error,\n                                             WalletSetupFn setup_wallet,\n-                                            WalletCheckFn check_before_create)\n+                                            WalletCheckFn check_before_create,\n+                                            std::shared_ptr<RescanControl> import_control)\n {\n     const QString wallet_name = name.trimmed();\n     if (setup_wallet) {\n@@ -676,17 +759,28 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             const auto error = util::ErrorString(wallet);\n             out.error = QString::fromStdString(error.translated.empty() ? error.original : error.translated);\n             if (out.error.isEmpty()) out.error = tr(\"Wallet creation failed.\");\n-        } else if (setup_wallet && !(out.error = setup_wallet(**wallet)).isEmpty()) {\n-            DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n-            SetPendingImport(wallet_name.toStdString(), std::nullopt);\n+        } else if (bool keep_wallet{false}; setup_wallet && !(out.error = setup_wallet(**wallet, keep_wallet)).isEmpty()) {\n+            if (!keep_wallet) {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }\n         } else {\n             out.wallet = std::move(*wallet);\n         }\n         return out;\n-    }, [this, wallet_name, load_action, report_create_error](WalletCommandResult out) {\n+    }, [this, wallet_name, load_action, report_create_error, import_control](WalletCommandResult out) {\n         if (m_deferred_wallet_name == wallet_name) m_deferred_wallet_name.clear();\n         setWalletLoadWarnings(out.warnings);\n         setWalletLoadInProgress(false);\n+        // A cancel can arrive after the worker last checked for one.\n+        if (out.wallet && import_control && import_control->cancelled()) {\n+            setWalletLoadError(tr(\"The import was cancelled, and its wallet was deleted.\"));\n+            m_wallet_command_executor->submit(this, [node = &m_node, wallet = std::move(out.wallet), wallet_name]() mutable {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }, [] {});\n+            return;\n+        }\n         if (!out.wallet) {\n             if (report_create_error) setWalletCreateError(out.error);\n             else setWalletLoadError(out.error);\n@@ -825,9 +919,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n     }\n     const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n-    // An unset timestamp means now.\n-    int64_t rescan_from{QDateTime::currentSecsSinceEpoch()};\n-    for (const auto& request : input.requests) rescan_from = std::min(rescan_from, request.timestamp.value_or(rescan_from));\n     std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n     auto control{std::make_shared<RescanControl>()};\n     m_import_control = control;\n@@ -837,14 +928,28 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                       creation_flags,\n                       WalletLoadAction::Create,\n                       /*report_create_error=*/false,\n-                      [node = &m_node, requests, rescan_from, control, guard = QPointer{this},\n-                       bridge = m_notification_bridge](interfaces::Wallet& wallet) mutable {\n+                      [node = &m_node, requests, control, guard = QPointer{this},\n+                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n-        SetPendingImport(wallet.getWalletName(), rescan_from);\n+        // The abort refers to this wallet, which is gone once this returns or throws.\n+        const auto detach{qScopeGuard([&control] { control->detach(); })};\n+        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n+        // Resolved here, so the marker starts where the wallet's rescan does.\n+        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n+        // Without the marker, a crash during the rescan would leave the wallet missing history unnoticed.\n+        if (!SetPendingImport(path, PendingImport{start, /*installed=*/false})) {\n+            return WalletQmlController::tr(\"The app couldn't save its settings, which it needs to finish the import if it closes during it. Check that its settings can be written, then try again.\");\n+        }\n         std::vector<wallet::ImportResult> results;\n         {\n-            const auto progress{wallet.handleShowProgress([&wallet, control, guard, bridge](const std::string&, int percent) {\n+            // The rescan starts after every request is handled, even when some failed.\n+            bool checked{false};\n+            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n+                if (!std::exchange(checked, true)) {\n+                    const wallet::CWallet* raw_wallet{wallet.wallet()};\n+                    if (raw_wallet && DescriptorsSaved(*raw_wallet, requests)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                }\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -854,14 +959,17 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             // Imports the descriptors, then rescans from the oldest timestamp.\n             results = wallet.importDescriptors(requests);\n         }\n-        control->detach();\n         if (control->cancelled()) return cancelled;\n-        // Shutdown stops the rescan early without an error, which would keep a wallet missing history.\n-        if (node->shutdownRequested()) return WalletQmlController::tr(\"The import was interrupted before it found all transactions.\");\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n         }\n-        SetPendingImport(wallet.getWalletName(), std::nullopt);\n+        // Shutdown stops the rescan early without an error. The next start finishes it.\n+        if (node->shutdownRequested()) {\n+            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+            keep_wallet = true;\n+            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n+        }\n+        SetPendingImport(path, std::nullopt);\n         return QString{};\n     }, [node = &m_node, oldest_dated, chosen_date] {\n         // Checked before the wallet file exists, so another date can be tried with the same name.\n@@ -874,7 +982,7 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             return WalletQmlController::tr(\"This node no longer has the blocks from when this wallet was created, so it can't find the older transactions. Choose a later date, or import it on a node that keeps all blocks.\");\n         }\n         return QString{};\n-    });\n+    }, control);\n }\n \n void WalletQmlController::importWallet(const QString& path)\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144Editing during an import hides the cancellation controlqml/pages/wallet/CreateWalletForm.qmladdressed
Assessment

The wallet-name and descriptor inputs, as well as the address-type and birth-date sections, are disabled while creation is running, preventing edits from clearing load status or changing the displayed import during the worker operation.

path_diff: qml/pages/wallet/CreateWalletForm.qml; new_source: qml/pages/wallet/CreateWalletForm.qml

[
  {
    "evidence_id": "b833d9d8930544d993600ed5bc4c91e2",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/pages/wallet/CreateWalletForm.qml",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/pages/wallet/CreateWalletForm.qml b/qml/pages/wallet/CreateWalletForm.qml\nindex a2b36f3b3f..5fb58b3929 100644\n--- a/qml/pages/wallet/CreateWalletForm.qml\n+++ b/qml/pages/wallet/CreateWalletForm.qml\n@@ -160,6 +160,8 @@ OnboardingView {\n         LabeledTextField {\n             id: nameEntry\n             objectName: \"createWalletNameEntry\"\n+            // Editing clears the load status, which would hide Cancel import.\n+            enabled: !root.creating\n             Layout.fillWidth: true\n             label: qsTr(\"Wallet name\")\n             fieldObjectName: \"createWalletNameInput\"\n@@ -251,6 +253,7 @@ OnboardingView {\n             id: xpubEntry\n             objectName: \"createWalletXpubEntry\"\n             visible: root.watchOnly\n+            enabled: !root.creating\n             Layout.fillWidth: true\n             label: qsTr(\"Descriptors or extended public key\")\n             inputObjectName: \"watchOnlyXpubInput\"\n@@ -394,6 +397,7 @@ OnboardingView {\n         FormSection {\n             objectName: \"watchOnlyAddressType\"\n             visible: root.watchOnly && root.needsAddressType\n+            enabled: !root.creating\n             Layout.fillWidth: true\n             Layout.topMargin: 8\n             showBackground: false\n@@ -428,6 +432,7 @@ OnboardingView {\n         FormSection {\n             objectName: \"watchOnlyBirthDate\"\n             visible: root.watchOnly && root.needsBirthDate\n+            enabled: !root.creating\n             Layout.fillWidth: true\n             Layout.topMargin: 8\n             showBackground: false\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "c839b915d5c043419936aea502b8c781",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 81,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/pages/wallet/CreateWalletForm.qml",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "    function submit() {\n        if (!canCreate) return\n        const availabilityError = walletController.walletNameAvailabilityError(loadedChildView.walletName)\n        if (availabilityError.length > 0) {\n            nameError = availabilityError\n            return\n        }\n        createRequested(loadedChildView.walletName.trim(), watchOnly ? loadedChildView.importText.trim() : \"\",\n            watchOnly || !loadedChildView.encryptWallet ? \"\" : loadedChildView.passwordText,\n            watchOnly ? birthTime() : -1,\n            watchOnly && needsAddressType ? loadedChildView.addressTypeChoice : \"\")\n    }\n\n    function clearSecrets() {\n        if (loadedChildView) loadedChildView.clearSecrets()\n    }\n\n    title: \"\"\n    heading: watchOnly ? qsTr(\"Watch-only wallet\") : qsTr(\"Single-key wallet\")\n    subheading: watchOnly\n        ? qsTr(\"See balances and activity without keeping spending keys in this app. An external signer is needed to spend.\")\n        : qsTr(\"You can control it in this application.\\nWallet data will be stored locally in your hard drive.\")\n    maximumContentWidth: 800\n    showBackButton: !creating && navigationStack\n        ? (navigationStack.canGoBack !== undefined\n            ? navigationStack.canGoBack : navigationStack.depth > 1) : false\n    showCloseButton: modalView && !creating\n    primaryButtonText: creating ? (watchOnly ? qsTr(\"Importing…\") : qsTr(\"Creating…\")) : qsTr(\"Create wallet\")\n    primaryButtonObjectName: \"createWalletFormCreateButton\"\n    primaryButtonEnabled: canCreate\n    readonly property bool importRunning: watchOnly && creating && walletController.walletLoadInProgress\n    secondaryButtonText: importRunning ? qsTr(\"Cancel import\") : \"\"\n    secondaryButtonObjectName: \"createWalletFormCancelImportButton\"\n    onSecondaryClicked: walletController.cancelViewOnlyImport()\n    onCloseClicked: root.cancel()\n    onPrimaryClicked: {\n        if (!root.canCreate) return\n        if (root.watchOnly || root.loadedChildView.encryptWallet) root.submit()\n        else root.loadedChildView.openUnencryptedWarning()\n    }\n\n    // Choices made for one key or set of descriptors do not carry over to another.\n    onImportIdChanged: {\n        if (importId.length === 0) return\n        if (previousImportId.length > 0 && importId !== previousImportId && loadedChildView) {\n            loadedChildView.addressTypeChoice = \"\"\n            loadedChildView.birthChoice = \"\"\n        }\n        previousImportId = importId\n    }\n\n    Component.onCompleted: {\n        walletController.clearWalletCreateStatus()\n        walletController.clearWalletLoadStatus()\n    }\n    Component.onDestruction: clearSecrets()\n\n    childView: ColumnLayout {\n        id: fields\n        property alias walletName: nameEntry.text\n        property alias importText: xpubEntry.text\n        property string addressTypeChoice: \"\"\n        property string birthChoice: \"\"\n        property alias encryptWallet: encryptCheck.checked\n        property alias passwordText: passwordEntry.text\n        property alias confirmText: confirmEntry.text\n        readonly property bool passwordLossAcknowledged: acknowledgement.checked\n        readonly property bool unencryptedWalletAcknowledged: unencryptedAcknowledgement.checked\n\n        function clearSecrets() {\n            passwordEntry.text = \"\"\n            confirmEntry.text = \"\"\n        }\n        function openUnencryptedWarning() {\n            unencryptedWarning.open()\n        }\n\n        spacing: 16\n\n        LabeledTextField {\n            id: nameEntry\n            objectName: \"createWalletNameEntry\"\n            // Editing clears the load status, which would hide Cancel import.\n            enabled: !root.creating\n            Layout.fillWidth: true\n            label: qsTr(\"Wallet name\")\n            fieldObjectName: \"createWalletNameInput\"\n            placeholderText: qsTr(\"e.g. My bitcoin wallet\")\n            supportingText: qsTr(\"You cannot change this later.\")\n            fieldSurface: true\n            labelSpacing: 6\n            messageSpacing: 8\n            fieldBackgroundColor: Theme.color.surface2\n            onTextEdited: {\n                root.nameError = \"\"\n                walletController.clearWalletCreateStatus()\n                walletController.clearWalletLoadStatus()\n            }\n        }\n\n        // Consent in a form is a checkbox; nothing applies until Create.\n        FormSection {\n            objectName: \"createWalletSecuritySection\"\n            visible: !root.watchOnly\n            Layout.fillWidth: true\n            Layout.topMargin: 8\n            showBackground: false\n            title: qsTr(\"Security\")\n            rowSpacing: 16\n\n            CheckBox {\n                id: encryptCheck\n                objectName: \"createWalletEncryptCheckBox\"\n                Layout.fillWidth: true\n                text: qsTr(\"Encrypt this wallet with a strong password.\")\n                description: qsTr(\"Recommended\")\n                checked: true\n                onCheckedChanged: {\n                    if (!checked) acknowledgement.checked = false\n                    if (checked) unencryptedAcknowledgement.checked = false\n                }\n            }\n\n            PasswordTextField {\n                id: passwordEntry\n                objectName: \"createWalletPasswordEntry\"\n                visible: encryptCheck.checked\n                Layout.fillWidth: true\n                label: qsTr(\"Password\")\n                fieldObjectName: \"createWalletPasswordInput\"\n                placeholderText: qsTr(\"Enter password…\")\n                fieldSurface: true\n                labelSpacing: 6\n                messageSpacing: 8\n                fieldBackgroundColor: Theme.color.surface2\n                onTextEdited: walletController.clearWalletCreateStatus()\n            }\n            PasswordTextField {\n                id: confirmEntry\n                objectName: \"createWalletConfirmPasswordEntry\"\n                visible: encryptCheck.checked\n                Layout.fillWidth: true\n                label: qsTr(\"Confirm password\")\n                fieldObjectName: \"createWalletPasswordRepeatInput\"\n                placeholderText: qsTr(\"Enter password again…\")\n                fieldSurface: true\n                labelSpacing: 6\n                messageSpacing: 8\n                fieldBackgroundColor: Theme.color.surface2\n                errorText: text.length > 0 && passwordEntry.text !== text",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1144Quitting during the import discards a recoverable walletqml/walletqmlcontroller.cppaddressed
Assessment

When shutdown interrupts the initial rescan after installation, the setup handler preserves the wallet and writes an installed pending marker, allowing recovery on the next start rather than discarding the wallet and marker.

path_diff: qml/walletqmlcontroller.cpp; new_source: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "cb9e56c3b8a549a1a84b806925ae3f1e",
    "finding_id": "finding:2",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 452a87cf64..81317bf10e 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -13,6 +13,7 @@\n #include <common/args.h>\n #include <common/settings.h>\n #include <interfaces/chain.h>\n+#include <interfaces/handler.h>\n #include <interfaces/node.h>\n #include <interfaces/wallet.h>\n #include <support/allocators/secure.h>\n@@ -45,6 +46,7 @@\n #include <QMetaObject>\n #include <QPointer>\n #include <QRegularExpression>\n+#include <QScopeGuard>\n #include <QSettings>\n #include <QStringList>\n #include <QTimer>\n@@ -122,48 +124,94 @@ void DiscardCreatedWallet(interfaces::WalletLoader& loader, std::unique_ptr<inte\n \n // A view-only import saves its descriptors before it rescans. The wallet's\n // best block is already the tip then, so after a crash it would load without\n-// the older transactions. This records where the rescan starts until it ends.\n-QString PendingImportKey(const std::string& wallet_name)\n+// the older transactions. This records where the rescan starts until it ends,\n+// and whether every descriptor was saved.\n+struct PendingImport {\n+    int64_t start{0};\n+    bool installed{false};\n+};\n+\n+// The marker belongs to the wallet file, not to its name.\n+std::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n {\n-    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_name).toHex()));\n+    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n+    std::error_code error;\n+    const fs::path canonical{fs::weakly_canonical(path, error)};\n+    return fs::PathToString(error ? path : canonical);\n }\n \n-void SetPendingImport(const std::string& wallet_name, std::optional<int64_t> time)\n+QString PendingImportKey(const std::string& wallet_path)\n+{\n+    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n+}\n+\n+void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n-    if (time) {\n-        settings.setValue(PendingImportKey(wallet_name), qlonglong(*time));\n-    } else {\n-        settings.remove(PendingImportKey(wallet_name));\n+    const QString key{PendingImportKey(wallet_path)};\n+    settings.remove(key);\n+    if (pending) {\n+        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n+        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n }\n \n-std::optional<int64_t> PendingImport(const std::string& wallet_name)\n+std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n {\n-    const QVariant time{QSettings{}.value(PendingImportKey(wallet_name))};\n-    return time.isValid() ? std::optional<int64_t>{time.toLongLong()} : std::nullopt;\n+    QSettings settings;\n+    const QString key{PendingImportKey(wallet_path)};\n+    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n+    if (!start.isValid()) return std::nullopt;\n+    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n+}\n+\n+// What the wallet takes as now for an import: the median time of the tip.\n+int64_t ChainNow(interfaces::WalletLoader& loader)\n+{\n+    wallet::WalletContext* context{loader.context()};\n+    int64_t time{0};\n+    if (context && context->chain) {\n+        interfaces::Chain& chain{*context->chain};\n+        if (const std::optional<int> height{chain.getHeight()};\n+            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n+            return time;\n+        }\n+    }\n+    return QDateTime::currentSecsSinceEpoch();\n }\n \n-bool ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control)\n+ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                const std::function<void(int)>& progress)\n {\n+    using Status = ImportRescanResult::Status;\n     wallet::WalletContext* context{node.walletLoader().context()};\n     const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n-    if (!wallet) return false;\n+    if (!wallet) return {Status::Stopped};\n     wallet::WalletRescanReserver reserver{*wallet};\n-    if (!reserver.reserve()) return false;\n-    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return false;\n+    // Another rescan of this wallet is running.\n+    if (!reserver.reserve()) return {Status::Failed};\n+    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n+    // The abort refers to this frame, and Scan can throw.\n+    const auto detach{qScopeGuard([&control] { control.detach(); })};\n+    const auto progress_handler{interfaces::MakeSignalHandler(\n+        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n     int start_height{0};\n     uint256 start_block;\n-    bool done{!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n-                                                               interfaces::FoundBlock().hash(start_block).height(start_height))};\n-    if (!done) {\n-        // Progress is saved, so a later load continues from where this stopped too.\n-        done = wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true).status ==\n-               wallet::ScanResult::SUCCESS;\n+    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n+                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n+        return {Status::Done};\n+    }\n+    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n+    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n+    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n+    ImportRescanResult stopped{Status::Stopped};\n+    int64_t last_time{0};\n+    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n+        stopped.checkpoint = last_time;\n     }\n-    control.detach();\n-    return done;\n+    return stopped;\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -214,8 +262,9 @@ WalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent\n     , m_open_local_path_fn([](const QString& path) {\n         return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n     })\n-    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control) {\n-        return ResumeImport(node, wallet_name, time, control);\n+    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                 const std::function<void(int)>& progress) {\n+        return ResumeImport(node, wallet_name, time, control, progress);\n     })\n {\n     m_empty_wallet->setNode(&m_node);\n@@ -524,8 +573,15 @@ void WalletQmlController::registerWalletModel(WalletQmlModel* wallet_model)\n void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n {\n     const QString name{wallet_model->name()};\n-    const std::optional<int64_t> time{PendingImport(name.toStdString())};\n-    if (!time) return;\n+    if (m_import_rescans.contains(name)) return;\n+    const std::string path{WalletPath(m_node.walletLoader(), name.toStdString())};\n+    const std::optional<PendingImport> pending{ReadPendingImport(path)};\n+    if (!pending) return;\n+    // Rescanning can't add the descriptors that were never saved.\n+    if (!pending->installed) {\n+        wallet_model->setHistoryRecovery(QStringLiteral(\"incomplete\"));\n+        return;\n+    }\n     if (!m_import_rescan_executor) {\n         m_import_rescan_executor = std::make_unique<BackendExecutor>();\n         m_import_rescan_executor->setObjectName(QStringLiteral(\"wallet-import-rescan\"));\n@@ -537,15 +593,43 @@ void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n     }\n     auto control{std::make_shared<RescanControl>()};\n     m_import_rescans[name] = control;\n-    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), time = *time, control] {\n-        // Stays pending when the rescan stops early, so the next load tries again.\n-        if (resume(name, time, *control)) SetPendingImport(name, std::nullopt);\n-    }, [this, name, control] {\n+    wallet_model->setHistoryRecovery(QStringLiteral(\"running\"));\n+    const QPointer<WalletQmlModel> model{wallet_model};\n+    auto progress = [bridge = m_notification_bridge, model](int percent) {\n+        QMetaObject::invokeMethod(bridge.get(), [model, percent] {\n+            if (model) model->setHistoryRecovery(QStringLiteral(\"running\"), percent < 100 ? percent : -1);\n+        }, Qt::QueuedConnection);\n+    };\n+    const auto finished = [this, name, control, model](bool failed) {\n         const auto it{m_import_rescans.find(name)};\n         if (it != m_import_rescans.end() && it->second == control) m_import_rescans.erase(it);\n+        if (model) model->setHistoryRecovery(failed ? QStringLiteral(\"failed\") : QString{});\n+    };\n+    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), path, start = pending->start,\n+                                            control, progress = std::move(progress)] {\n+        using Status = ImportRescanResult::Status;\n+        const ImportRescanResult result{resume(name, start, *control, progress)};\n+        if (result.status == Status::Done) {\n+            SetPendingImport(path, std::nullopt);\n+        } else if (result.status == Status::Stopped && result.checkpoint && *result.checkpoint > start) {\n+            // The next rescan starts a window before the last block read.\n+            SetPendingImport(path, PendingImport{*result.checkpoint, /*installed=*/true});\n+        }\n+        // The marker stays otherwise, so the next load tries again.\n+        return result.status;\n+    }, [finished](ImportRescanResult::Status status) {\n+        finished(status != ImportRescanResult::Status::Done);\n+    }, [finished](std::exception_ptr) {\n+        finished(/*failed=*/true);\n     });\n }\n \n+void WalletQmlController::retryHistoryRecovery(WalletQmlModel* wallet)\n+{\n+    if (!wallet || m_shutting_down || wallet->historyRecovery() != QStringLiteral(\"failed\")) return;\n+    resumeInterruptedImport(wallet);\n+}\n+\n void WalletQmlController::removeWalletModel(WalletQmlModel* wallet_model, bool remove)\n {\n     if (!wallet_model || wallet_model == m_empty_wallet) {\n@@ -676,9 +760,11 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             const auto error = util::ErrorString(wallet);\n             out.error = QString::fromStdString(error.translated.empty() ? error.original : error.translated);\n             if (out.error.isEmpty()) out.error = tr(\"Wallet creation failed.\");\n-        } else if (setup_wallet && !(out.error = setup_wallet(**wallet)).isEmpty()) {\n-            DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n-            SetPendingImport(wallet_name.toStdString(), std::nullopt);\n+        } else if (bool keep_wallet{false}; setup_wallet && !(out.error = setup_wallet(**wallet, keep_wallet)).isEmpty()) {\n+            if (!keep_wallet) {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }\n         } else {\n             out.wallet = std::move(*wallet);\n         }\n@@ -825,9 +911,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n     }\n     const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n-    // An unset timestamp means now.\n-    int64_t rescan_from{QDateTime::currentSecsSinceEpoch()};\n-    for (const auto& request : input.requests) rescan_from = std::min(rescan_from, request.timestamp.value_or(rescan_from));\n     std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n     auto control{std::make_shared<RescanControl>()};\n     m_import_control = control;\n@@ -837,14 +920,20 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                       creation_flags,\n                       WalletLoadAction::Create,\n                       /*report_create_error=*/false,\n-                      [node = &m_node, requests, rescan_from, control, guard = QPointer{this},\n-                       bridge = m_notification_bridge](interfaces::Wallet& wallet) mutable {\n+                      [node = &m_node, requests, control, guard = QPointer{this},\n+                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n-        SetPendingImport(wallet.getWalletName(), rescan_from);\n+        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n+        // Resolved here, so the marker starts where the wallet's rescan does.\n+        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n+        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n         std::vector<wallet::ImportResult> results;\n         {\n-            const auto progress{wallet.handleShowProgress([&wallet, control, guard, bridge](const std::string&, int percent) {\n+            // The rescan starts once every descriptor is saved.\n+            bool installed{false};\n+            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n+                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -856,12 +945,16 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         }\n         control->detach();\n         if (control->cancelled()) return cancelled;\n-        // Shutdown stops the rescan early without an error, which would keep a wallet missing history.\n-        if (node->shutdownRequested()) return WalletQmlController::tr(\"The import was interrupted before it found all transactions.\");\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n         }\n-        SetPendingImport(wallet.getWalletName(), std::nullopt);\n+        // Shutdown stops the rescan early without an error. The next start finishes it.\n+        if (node->shutdownRequested()) {\n+            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+            keep_wallet = true;\n+            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n+        }\n+        SetPendingImport(path, std::nullopt);\n         return QString{};\n     }, [node = &m_node, oldest_dated, chosen_date] {\n         // Checked before the wallet file exists, so another date can be tried with the same name.\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 979,
    "evidence_id": "58b3a4aa42fe4296a85316ba753304cc",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 830,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "    if (!name_error.isEmpty()) {\n        setWalletLoadError(name_error);\n        return false;\n    }\n\n    refreshExternalSignerStatus();\n    if (!m_external_signer_path_configured) {\n        setWalletLoadError(tr(\"Set an external signer path in Wallet settings first.\"));\n        return false;\n    }\n    if (!m_external_signer_error.isEmpty()) {\n        setWalletLoadError(m_external_signer_error);\n        return false;\n    }\n    if (m_external_signer_count == 0) {\n        setWalletLoadError(tr(\"Connect an external signer and try again.\"));\n        return false;\n    }\n    if (m_external_signer_count > 1) {\n        setWalletLoadError(tr(\"More than one external signer was found. Connect only one device and try again.\"));\n        return false;\n    }\n\n    constexpr uint64_t flags = wallet::WALLET_FLAG_DESCRIPTORS |\n        wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS |\n        wallet::WALLET_FLAG_EXTERNAL_SIGNER;\n    createWalletAsync(wallet_name,\n                      SecureString{},\n                      flags,\n                      WalletLoadAction::Load,\n                      /*report_create_error=*/false);\n    return true;\n}\n\nvoid WalletQmlController::createWatchOnlyWallet(const QString& name, const QString& import_text, qint64 birth_time,\n                                                const QString& address_type)\n{\n    if (m_wallet_load_in_progress) {\n        return;\n    }\n    clearWalletLoadStatus();\n    clearWalletMigrationStatus();\n    if (!m_initialized) {\n        setWalletLoadError(tr(\"Wallets are still loading. Try again in a moment.\"));\n        return;\n    }\n\n    ViewOnlyImport input{ParseViewOnlyImport(import_text, address_type)};\n    if (input.kind == ViewOnlyImport::Kind::Empty) {\n        setWalletLoadError(tr(\"Enter descriptors, or an extended public key (xpub).\"));\n        return;\n    }\n    if (!input.error.isEmpty()) {\n        setWalletLoadError(input.error);\n        return;\n    }\n    if (input.requests.empty()) {\n        setWalletLoadError(tr(\"Choose the address type of this key.\"));\n        return;\n    }\n    if (!input.undated.empty()) {\n        if (birth_time < 0) {\n            setWalletLoadError(tr(\"Choose when this wallet was created.\"));\n            return;\n        }\n        for (const size_t index : input.undated) input.requests[index].timestamp = birth_time;\n    }\n\n    const QString name_error = walletNameAvailabilityError(name);\n    if (!name_error.isEmpty()) {\n        setWalletLoadError(name_error);\n        return;\n    }\n\n    const uint64_t creation_flags = wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS |\n                                    wallet::WALLET_FLAG_DESCRIPTORS |\n                                    wallet::WALLET_FLAG_BLANK_WALLET;\n    // Only undated requests take the chosen date, so a dated one can need pruned blocks whatever the date.\n    std::optional<int64_t> oldest_dated;\n    for (size_t i = 0; i < input.requests.size(); ++i) {\n        const std::optional<int64_t>& time{input.requests[i].timestamp};\n        if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n    }\n    const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n    std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n    auto control{std::make_shared<RescanControl>()};\n    m_import_control = control;\n    setImportProgress(-1);\n    createWalletAsync(name.trimmed(),\n                      SecureString{},\n                      creation_flags,\n                      WalletLoadAction::Create,\n                      /*report_create_error=*/false,\n                      [node = &m_node, requests, control, guard = QPointer{this},\n                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n        const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n        if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n        // Resolved here, so the marker starts where the wallet's rescan does.\n        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n        std::vector<wallet::ImportResult> results;\n        {\n            // The rescan starts once every descriptor is saved.\n            bool installed{false};\n            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n                // Starting a rescan clears an earlier abort.\n                if (control->cancelled()) wallet.abortRescan();\n                QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n                    if (guard) guard->setImportProgress(percent < 100 ? percent : -1);\n                }, Qt::QueuedConnection);\n            })};\n            // Imports the descriptors, then rescans from the oldest timestamp.\n            results = wallet.importDescriptors(requests);\n        }\n        control->detach();\n        if (control->cancelled()) return cancelled;\n        for (const wallet::ImportResult& result : results) {\n            if (result.has_error()) return ImportErrorText(*result.error);\n        }\n        // Shutdown stops the rescan early without an error. The next start finishes it.\n        if (node->shutdownRequested()) {\n            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n            keep_wallet = true;\n            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n        }\n        SetPendingImport(path, std::nullopt);\n        return QString{};\n    }, [node = &m_node, oldest_dated, chosen_date] {\n        // Checked before the wallet file exists, so another date can be tried with the same name.\n        wallet::WalletContext* context{node->walletLoader().context()};\n        if (!context || !context->chain) return QString{};\n        if (ScanBlocksPruned(*context->chain, oldest_dated)) {\n            return WalletQmlController::tr(\"This node no longer has the blocks from when these descriptors were created, so it can't find their older transactions. Import them on a node that keeps all blocks.\");\n        }\n        if (ScanBlocksPruned(*context->chain, chosen_date)) {\n            return WalletQmlController::tr(\"This node no longer has the blocks from when this wallet was created, so it can't find the older transactions. Choose a later date, or import it on a node that keeps all blocks.\");\n        }\n        return QString{};\n    });\n}\n\nvoid WalletQmlController::importWallet(const QString& path)\n{\n    if (!m_initialized) {\n        setWalletLoadError(tr(\"Wallets are still loading. Try again in a moment.\"));\n        return;\n    }\n    startWalletImport(path);",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1144Parser and row-grouping corrections are separated from their introductionsqml/viewonlyimport.cppunclear
Assessment

The requested changes concern combining fixes with their introducing commits. The source diff shows corrected final parser and row-grouping behavior, but does not establish whether the commits were rearranged as requested.

path_diff: qml/viewonlyimport.cpp

[
  {
    "evidence_id": "b11d18479003455ebabefa81411a27b7",
    "finding_id": "finding:13",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/viewonlyimport.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/viewonlyimport.cpp b/qml/viewonlyimport.cpp\nindex 4dbb3041d2..12e54f0f5b 100644\n--- a/qml/viewonlyimport.cpp\n+++ b/qml/viewonlyimport.cpp\n@@ -31,6 +31,9 @@\n \n using wallet::ImportDescriptorRequest;\n \n+// As many keys as the wallet allows in one range.\n+constexpr int64_t MAX_RANGE_END{1'000'000};\n+\n namespace {\n \n struct DescriptorCheck {\n@@ -201,6 +204,12 @@ ViewOnlyImport ParseJson(const std::string& text)\n                 if (const auto bounds{CheckDescriptorRangeBounds(request.range->first, request.range->second)}; !bounds) {\n                     return Failed(Kind::DescriptorJson, QStringLiteral(\"%1: %2\").arg(position, QString::fromStdString(bounds.error())));\n                 }\n+                // The wallet derives every key from index 0 to the end, while it blocks and can't be cancelled.\n+                if (request.range->second >= MAX_RANGE_END) {\n+                    //: %2 is the highest index that can be imported.\n+                    return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a range that ends after %2, which would take too long to set up.\")\n+                                                            .arg(position).arg(MAX_RANGE_END - 1));\n+                }\n             }\n             const UniValue& next_index{entry.find_value(\"next_index\")};\n             const UniValue& next{next_index.isNull() ? entry.find_value(\"next\") : next_index};\n@@ -220,9 +229,12 @@ ViewOnlyImport ParseJson(const std::string& text)\n             if (!request.label.empty() && (check.ranged || multipath || request.internal.value_or(false))) {\n                 return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a label, but only a single receive address can have one.\").arg(position));\n             }\n+            // Without a range, the wallet's keypool size bounds it, which isn't known here.\n+            if (request.next_index && !request.range) {\n+                return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index but no range.\").arg(position));\n+            }\n             if (check.ranged && request.next_index) {\n-                const int64_t first{request.range ? request.range->first : 0};\n-                if (*request.next_index < first || (request.range && *request.next_index > request.range->second)) {\n+                if (*request.next_index < request.range->first || *request.next_index > request.range->second) {\n                     return Failed(Kind::DescriptorJson, QObject::tr(\"%1 has a next index outside its range.\").arg(position));\n                 }\n             }\n@@ -321,6 +333,8 @@ const std::array KNOWN_KEY_VERSIONS{\n // [fingerprint/path]key, the key origin form wallets export.\n const QRegularExpression KEY_ORIGIN{QStringLiteral(R\"(^\\[([0-9a-fA-F]{8})((?:/[0-9]+['hH]?)*)\\]([1-9A-HJ-NP-Za-km-z]+)$)\")};\n const QRegularExpression ORIGIN_PURPOSE{QStringLiteral(R\"(^/(44|49|84|86)['hH])\")};\n+// BIP45 and BIP48 are multisig cosigner paths.\n+const QRegularExpression MULTISIG_PURPOSE{QStringLiteral(R\"(^/(45|48)['hH])\")};\n \n struct ExtendedKey {\n     bool recognized{false};\n@@ -394,6 +408,9 @@ ViewOnlyImport ParseExtendedKey(const ExtendedKey& key, const QString& origin, c\n {\n     using Kind = ViewOnlyImport::Kind;\n     if (!key.error.isEmpty()) return Failed(Kind::ExtendedKey, key.error);\n+    if (MULTISIG_PURPOSE.match(path).hasMatch()) {\n+        return Failed(Kind::ExtendedKey, QObject::tr(\"This key is from a multisig wallet. Only single-key wallets can be imported.\"));\n+    }\n     // The key's prefix wins, then a BIP44, 49, 84 or 86 path.\n     const std::optional<OutputType> path_type{PurposeType(path)};\n     std::optional<OutputType> type{key.type ? key.type : path_type};\n@@ -476,8 +493,10 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n             active_slots[{type, request.internal.value_or(false)}] = i;\n         }\n     }\n-    std::vector<bool> active(parsed.requests.size(), false);\n-    for (const auto& [slot, index] : active_slots) active[index] = true;\n+    const auto branch_active = [&](size_t i, bool change) {\n+        const auto slot{active_slots.find({parsed.sources[i].type, change})};\n+        return slot != active_slots.end() && slot->second == i;\n+    };\n     QString warning{parsed.warning};\n     if (warning.isEmpty() && std::ranges::none_of(active_slots, [](const auto& slot) { return slot.first.second; })) {\n         bool watches_change{false};\n@@ -489,7 +508,7 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n             : QObject::tr(\"Nothing here is for change addresses. Payments to the other wallet's change won't show, and this wallet can't prepare a transaction that needs change.\");\n     }\n \n-    // Receive and change of one key share a row.\n+    // Receive and change of one key share a row, unless only one of them stays active.\n     QVariantList rows;\n     QStringList row_keys;\n     for (size_t i = 0; i < parsed.requests.size(); ++i) {\n@@ -501,34 +520,36 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n         if (time) created = std::min(created.value_or(*time), *time);\n \n         const QString type{QmlUtil::OutputTypeLabel(source.type)};\n-        auto row_it{rows.begin()};\n-        for (; row_it != rows.end(); ++row_it) {\n-            const QVariantMap map{row_it->toMap()};\n-            if (map.value(QStringLiteral(\"addressType\")) == type && row_keys[std::distance(rows.begin(), row_it)] == source.key_id &&\n-                map.value(QStringLiteral(\"active\")) == bool(active[i]) && map.value(QStringLiteral(\"ranged\")) == source.ranged) {\n-                break;\n+        const std::vector<bool> branches{source.multipath ? std::vector<bool>{false, true} : std::vector<bool>{request.internal.value_or(false)}};\n+        for (const bool change : branches) {\n+            const bool active{branch_active(i, change)};\n+            auto row_it{rows.begin()};\n+            for (; row_it != rows.end(); ++row_it) {\n+                const QVariantMap map{row_it->toMap()};\n+                if (map.value(QStringLiteral(\"addressType\")) == type && row_keys[std::distance(rows.begin(), row_it)] == source.key_id &&\n+                    map.value(QStringLiteral(\"active\")) == active && map.value(QStringLiteral(\"ranged\")) == source.ranged) {\n+                    break;\n+                }\n             }\n+            if (row_it == rows.end()) {\n+                row_keys.append(source.key_id);\n+                rows.append(QVariantMap{{QStringLiteral(\"addressType\"), type},\n+                                        {QStringLiteral(\"key\"), source.key},\n+                                        {QStringLiteral(\"receive\"), false},\n+                                        {QStringLiteral(\"change\"), false},\n+                                        {QStringLiteral(\"active\"), active},\n+                                        {QStringLiteral(\"ranged\"), source.ranged},\n+                                        {QStringLiteral(\"createdTime\"), qlonglong(-1)}});\n+                row_it = std::prev(rows.end());\n+            }\n+            QVariantMap row{row_it->toMap()};\n+            row.insert(change ? QStringLiteral(\"change\") : QStringLiteral(\"receive\"), true);\n+            if (time) {\n+                const qlonglong row_time{row.value(QStringLiteral(\"createdTime\")).toLongLong()};\n+                row.insert(QStringLiteral(\"createdTime\"), row_time < 0 ? qlonglong(*time) : std::min(row_time, qlonglong(*time)));\n+            }\n+            *row_it = row;\n         }\n-        if (row_it == rows.end()) {\n-            row_keys.append(source.key_id);\n-            rows.append(QVariantMap{{QStringLiteral(\"addressType\"), type},\n-                                    {QStringLiteral(\"key\"), source.key},\n-                                    {QStringLiteral(\"receive\"), false},\n-                                    {QStringLiteral(\"change\"), false},\n-                                    {QStringLiteral(\"active\"), bool(active[i])},\n-                                    {QStringLiteral(\"ranged\"), source.ranged},\n-                                    {QStringLiteral(\"createdTime\"), qlonglong(-1)}});\n-            row_it = std::prev(rows.end());\n-        }\n-        QVariantMap row{row_it->toMap()};\n-        const bool change{request.internal.value_or(false)};\n-        if (source.multipath || !change) row.insert(QStringLiteral(\"receive\"), true);\n-        if (source.multipath || change) row.insert(QStringLiteral(\"change\"), true);\n-        if (time) {\n-            const qlonglong row_time{row.value(QStringLiteral(\"createdTime\")).toLongLong()};\n-            row.insert(QStringLiteral(\"createdTime\"), row_time < 0 ? qlonglong(*time) : std::min(row_time, qlonglong(*time)));\n-        }\n-        *row_it = row;\n     }\n     QStringList descriptors;\n     for (const ImportDescriptorRequest& request : parsed.requests) descriptors.append(QString::fromStdString(request.descriptor));\n@@ -552,3 +573,28 @@ QVariantMap DescribeViewOnlyImport(const QString& text, const QString& address_t\n     }\n     return result;\n }\n+\n+int64_t ResolveImportTimes(std::vector<ImportDescriptorRequest>& requests, int64_t now)\n+{\n+    int64_t oldest{now};\n+    for (ImportDescriptorRequest& request : requests) {\n+        request.timestamp = request.timestamp.value_or(now);\n+        oldest = std::min(oldest, *request.timestamp);\n+    }\n+    return oldest;\n+}\n+\n+bool DescriptorsSaved(const wallet::CWallet& wallet, const std::vector<ImportDescriptorRequest>& requests)\n+{\n+    LOCK(wallet.cs_wallet);\n+    for (const ImportDescriptorRequest& request : requests) {\n+        FlatSigningProvider keys;\n+        std::string error;\n+        auto parsed{Parse(request.descriptor, keys, error, /*require_checksum=*/false)};\n+        if (parsed.empty()) return false;\n+        for (auto& descriptor : parsed) {\n+            if (!wallet.GetDescriptorScriptPubKeyMan(wallet::WalletDescriptor{std::move(descriptor), 0, 0, 0, 0})) return false;\n+        }\n+    }\n+    return true;\n+}\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144Pruning preflight is immediately revised by the next commitqml/walletqmlcontroller.cppunclear
Assessment

The finding is about folding adjacent commits together. The supplied evidence establishes revised final-tree behavior but does not establish commit sequencing.

path_diff: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "cd35cab5cd9f4aaa86b6c91a55a90e6a",
    "finding_id": "finding:12",
    "kind": "path_diff",
    "new_head": "46324d90762c97b30dfdb35e944c7b2b1955ec4b",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 452a87cf64..08c013c361 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -13,6 +13,7 @@\n #include <common/args.h>\n #include <common/settings.h>\n #include <interfaces/chain.h>\n+#include <interfaces/handler.h>\n #include <interfaces/node.h>\n #include <interfaces/wallet.h>\n #include <support/allocators/secure.h>\n@@ -45,6 +46,7 @@\n #include <QMetaObject>\n #include <QPointer>\n #include <QRegularExpression>\n+#include <QScopeGuard>\n #include <QSettings>\n #include <QStringList>\n #include <QTimer>\n@@ -122,48 +124,92 @@ void DiscardCreatedWallet(interfaces::WalletLoader& loader, std::unique_ptr<inte\n \n // A view-only import saves its descriptors before it rescans. The wallet's\n // best block is already the tip then, so after a crash it would load without\n-// the older transactions. This records where the rescan starts until it ends.\n-QString PendingImportKey(const std::string& wallet_name)\n+// the older transactions. This records where the rescan starts until it ends,\n+// and whether every descriptor was saved.\n+struct PendingImport {\n+    int64_t start{0};\n+    bool installed{false};\n+};\n+\n+// The marker belongs to the wallet file, not to its name.\n+std::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n+{\n+    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n+    std::error_code error;\n+    const fs::path canonical{fs::weakly_canonical(path, error)};\n+    return fs::PathToString(error ? path : canonical);\n+}\n+\n+QString PendingImportKey(const std::string& wallet_path)\n {\n-    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_name).toHex()));\n+    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n }\n \n-void SetPendingImport(const std::string& wallet_name, std::optional<int64_t> time)\n+bool SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n-    if (time) {\n-        settings.setValue(PendingImportKey(wallet_name), qlonglong(*time));\n-    } else {\n-        settings.remove(PendingImportKey(wallet_name));\n+    const QString key{PendingImportKey(wallet_path)};\n+    settings.remove(key);\n+    if (pending) {\n+        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n+        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n+    return settings.status() == QSettings::NoError;\n }\n \n-std::optional<int64_t> PendingImport(const std::string& wallet_name)\n+std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n {\n-    const QVariant time{QSettings{}.value(PendingImportKey(wallet_name))};\n-    return time.isValid() ? std::optional<int64_t>{time.toLongLong()} : std::nullopt;\n+    QSettings settings;\n+    const QString key{PendingImportKey(wallet_path)};\n+    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n+    if (!start.isValid()) return std::nullopt;\n+    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n }\n \n-bool ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control)\n+// What the wallet takes as now for an import: the median time of the tip.\n+int64_t ChainNow(interfaces::WalletLoader& loader)\n {\n+    wallet::WalletContext* context{loader.context()};\n+    int64_t time{0};\n+    if (context && context->chain) {\n+        interfaces::Chain& chain{*context->chain};\n+        if (const std::optional<int> height{chain.getHeight()};\n+            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n+            return time;\n+        }\n+    }\n+    return QDateTime::currentSecsSinceEpoch();\n+}\n+\n+ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                const std::function<void(int)>& progress)\n+{\n+    using Status = ImportRescanResult::Status;\n     wallet::WalletContext* context{node.walletLoader().context()};\n     const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n-    if (!wallet) return false;\n+    if (!wallet) return {Status::Stopped};\n     wallet::WalletRescanReserver reserver{*wallet};\n-    if (!reserver.reserve()) return false;\n-    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return false;\n+    // Another rescan of this wallet is running.\n+    if (!reserver.reserve()) return {Status::Failed};\n+    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n+    // The abort refers to this frame, and Scan can throw.\n+    const auto detach{qScopeGuard([&control] { control.detach(); })};\n+    const auto progress_handler{interfaces::MakeSignalHandler(\n+        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n     int start_height{0};\n     uint256 start_block;\n-    bool done{!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n-                                                               interfaces::FoundBlock().hash(start_block).height(start_height))};\n-    if (!done) {\n-        // Progress is saved, so a later load continues from where this stopped too.\n-        done = wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true).status ==\n-               wallet::ScanResult::SUCCESS;\n+    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n+                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n+        return {Status::Done};\n     }\n-    control.detach();\n-    return done;\n+    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n+    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n+    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n+    int64_t last_time{0};\n+    const bool checkpoint{result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+                          wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))};\n+    return {Status::Stopped, checkpoint ? std::optional<int64_t>{last_time} : std::nullopt};\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -214,8 +260,9 @@ WalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent\n     , m_open_local_path_fn([](const QString& path) {\n         return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n     })\n-    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control) {\n-        return ResumeImport(node, wallet_name, time, control);\n+    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                 const std::function<void(int)>& progress) {\n+        return ResumeImport(node, wallet_name, time, control, progress);\n     })\n {\n     m_empty_wallet->setNode(&m_node);\n@@ -524,8 +571,15 @@ void WalletQmlController::registerWalletModel(WalletQmlModel* wallet_model)\n void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n {\n     const QString name{wallet_model->name()};\n-    const std::optional<int64_t> time{PendingImport(name.toStdString())};\n-    if (!time) return;\n+    if (m_import_rescans.contains(name)) return;\n+    const std::string path{WalletPath(m_node.walletLoader(), name.toStdString())};\n+    const std::optional<PendingImport> pending{ReadPendingImport(path)};\n+    if (!pending) return;\n+    // Rescanning can't add the descriptors that were never saved.\n+    if (!pending->installed) {\n+        wallet_model->setHistoryRecovery(QStringLiteral(\"incomplete\"));\n+        return;\n+    }\n     if (!m_import_rescan_executor) {\n         m_import_rescan_executor = std::make_unique<BackendExecutor>();\n         m_import_rescan_executor->setObjectName(QStringLiteral(\"wallet-import-rescan\"));\n@@ -537,15 +591,43 @@ void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n     }\n     auto control{std::make_shared<RescanControl>()};\n     m_import_rescans[name] = control;\n-    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), time = *time, control] {\n-        // Stays pending when the rescan stops early, so the next load tries again.\n-        if (resume(name, time, *control)) SetPendingImport(name, std::nullopt);\n-    }, [this, name, control] {\n+    wallet_model->setHistoryRecovery(QStringLiteral(\"running\"));\n+    const QPointer<WalletQmlModel> model{wallet_model};\n+    auto progress = [bridge = m_notification_bridge, model](int percent) {\n+        QMetaObject::invokeMethod(bridge.get(), [model, percent] {\n+            if (model) model->setHistoryRecovery(QStringLiteral(\"running\"), percent < 100 ? percent : -1);\n+        }, Qt::QueuedConnection);\n+    };\n+    const auto finished = [this, name, control, model](bool failed) {\n         const auto it{m_import_rescans.find(name)};\n         if (it != m_import_rescans.end() && it->second == control) m_import_rescans.erase(it);\n+        if (model) model->setHistoryRecovery(failed ? QStringLiteral(\"failed\") : QString{});\n+    };\n+    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), path, start = pending->start,\n+                                            control, progress = std::move(progress)] {\n+        using Status = ImportRescanResult::Status;\n+        const ImportRescanResult result{resume(name, start, *control, progress)};\n+        if (result.status == Status::Done) {\n+            SetPendingImport(path, std::nullopt);\n+        } else if (result.status == Status::Stopped && result.checkpoint && *result.checkpoint > start) {\n+            // The next rescan starts a window before the last block read.\n+            SetPendingImport(path, PendingImport{*result.checkpoint, /*installed=*/true});\n+        }\n+        // The marker stays otherwise, so the next load tries again.\n+        return result.status;\n+    }, [finished](ImportRescanResult::Status status) {\n+        finished(status != ImportRescanResult::Status::Done);\n+    }, [finished](std::exception_ptr) {\n+        finished(/*failed=*/true);\n     });\n }\n \n+void WalletQmlController::retryHistoryRecovery(WalletQmlModel* wallet)\n+{\n+    if (!wallet || m_shutting_down || wallet->historyRecovery() != QStringLiteral(\"failed\")) return;\n+    resumeInterruptedImport(wallet);\n+}\n+\n void WalletQmlController::removeWalletModel(WalletQmlModel* wallet_model, bool remove)\n {\n     if (!wallet_model || wallet_model == m_empty_wallet) {\n@@ -652,7 +734,8 @@ void WalletQmlController::createWalletAsync(const QString& name,\n                                             WalletLoadAction load_action,\n                                             bool report_create_error,\n                                             WalletSetupFn setup_wallet,\n-                                            WalletCheckFn check_before_create)\n+                                            WalletCheckFn check_before_create,\n+                                            std::shared_ptr<RescanControl> import_control)\n {\n     const QString wallet_name = name.trimmed();\n     if (setup_wallet) {\n@@ -676,17 +759,28 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             const auto error = util::ErrorString(wallet);\n             out.error = QString::fromStdString(error.translated.empty() ? error.original : error.translated);\n             if (out.error.isEmpty()) out.error = tr(\"Wallet creation failed.\");\n-        } else if (setup_wallet && !(out.error = setup_wallet(**wallet)).isEmpty()) {\n-            DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n-            SetPendingImport(wallet_name.toStdString(), std::nullopt);\n+        } else if (bool keep_wallet{false}; setup_wallet && !(out.error = setup_wallet(**wallet, keep_wallet)).isEmpty()) {\n+            if (!keep_wallet) {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }\n         } else {\n             out.wallet = std::move(*wallet);\n         }\n         return out;\n-    }, [this, wallet_name, load_action, report_create_error](WalletCommandResult out) {\n+    }, [this, wallet_name, load_action, report_create_error, import_control](WalletCommandResult out) {\n         if (m_deferred_wallet_name == wallet_name) m_deferred_wallet_name.clear();\n         setWalletLoadWarnings(out.warnings);\n         setWalletLoadInProgress(false);\n+        // A cancel can arrive after the worker last checked for one.\n+        if (out.wallet && import_control && import_control->cancelled()) {\n+            setWalletLoadError(tr(\"The import was cancelled, and its wallet was deleted.\"));\n+            m_wallet_command_executor->submit(this, [node = &m_node, wallet = std::move(out.wallet), wallet_name]() mutable {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }, [] {});\n+            return;\n+        }\n         if (!out.wallet) {\n             if (report_create_error) setWalletCreateError(out.error);\n             else setWalletLoadError(out.error);\n@@ -825,9 +919,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n     }\n     const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n-    // An unset timestamp means now.\n-    int64_t rescan_from{QDateTime::currentSecsSinceEpoch()};\n-    for (const auto& request : input.requests) rescan_from = std::min(rescan_from, request.timestamp.value_or(rescan_from));\n     std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n     auto control{std::make_shared<RescanControl>()};\n     m_import_control = control;\n@@ -837,14 +928,28 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                       creation_flags,\n                       WalletLoadAction::Create,\n                       /*report_create_error=*/false,\n-                      [node = &m_node, requests, rescan_from, control, guard = QPointer{this},\n-                       bridge = m_notification_bridge](interfaces::Wallet& wallet) mutable {\n+                      [node = &m_node, requests, control, guard = QPointer{this},\n+                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n-        SetPendingImport(wallet.getWalletName(), rescan_from);\n+        // The abort refers to this wallet, which is gone once this returns or throws.\n+        const auto detach{qScopeGuard([&control] { control->detach(); })};\n+        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n+        // Resolved here, so the marker starts where the wallet's rescan does.\n+        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n+        // Without the marker, a crash during the rescan would leave the wallet missing history unnoticed.\n+        if (!SetPendingImport(path, PendingImport{start, /*installed=*/false})) {\n+            return WalletQmlController::tr(\"The app couldn't save its settings, which it needs to finish the import if it closes during it. Check that its settings can be written, then try again.\");\n+        }\n         std::vector<wallet::ImportResult> results;\n         {\n-            const auto progress{wallet.handleShowProgress([&wallet, control, guard, bridge](const std::string&, int percent) {\n+            // The rescan starts after every request is handled, even when some failed.\n+            bool checked{false};\n+            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n+                if (!std::exchange(checked, true)) {\n+                    const wallet::CWallet* raw_wallet{wallet.wallet()};\n+                    if (raw_wallet && DescriptorsSaved(*raw_wallet, requests)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+                }\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -854,14 +959,17 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             // Imports the descriptors, then rescans from the oldest timestamp.\n             results = wallet.importDescriptors(requests);\n         }\n-        control->detach();\n         if (control->cancelled()) return cancelled;\n-        // Shutdown stops the rescan early without an error, which would keep a wallet missing history.\n-        if (node->shutdownRequested()) return WalletQmlController::tr(\"The import was interrupted before it found all transactions.\");\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n         }\n-        SetPendingImport(wallet.getWalletName(), std::nullopt);\n+        // Shutdown stops the rescan early without an error. The next start finishes it.\n+        if (node->shutdownRequested()) {\n+            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+            keep_wallet = true;\n+            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n+        }\n+        SetPendingImport(path, std::nullopt);\n         return QString{};\n     }, [node = &m_node, oldest_dated, chosen_date] {\n         // Checked before the wallet file exists, so another date can be tried with the same name.\n@@ -874,7 +982,7 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n             return WalletQmlController::tr(\"This node no longer has the blocks from when this wallet was created, so it can't find the older transactions. Choose a later date, or import it on a node that keeps all blocks.\");\n         }\n         return QString{};\n-    });\n+    }, control);\n }\n \n void WalletQmlController::importWallet(const QString& path)\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..46324d90762c

2026-11-25T22:14:12Z · gpt-6-luna

gui#1144Each interrupted recovery repeats the scan from its original startqml/walletqmlcontroller.cppaddressed
Assessment

On a stopped recovery scan, the code records a checkpoint from the last scanned block when no earlier block read failed; the next recovery uses the updated start. If the checkpoint is not safely later than the prior start, the marker remains unchanged.

path_diff: qml/walletqmlcontroller.cpp; new_source: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "8a9e4c54ac834b4d844e9c0124d4a4d5",
    "finding_id": "finding:11",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 452a87cf64..81317bf10e 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -13,6 +13,7 @@\n #include <common/args.h>\n #include <common/settings.h>\n #include <interfaces/chain.h>\n+#include <interfaces/handler.h>\n #include <interfaces/node.h>\n #include <interfaces/wallet.h>\n #include <support/allocators/secure.h>\n@@ -45,6 +46,7 @@\n #include <QMetaObject>\n #include <QPointer>\n #include <QRegularExpression>\n+#include <QScopeGuard>\n #include <QSettings>\n #include <QStringList>\n #include <QTimer>\n@@ -122,48 +124,94 @@ void DiscardCreatedWallet(interfaces::WalletLoader& loader, std::unique_ptr<inte\n \n // A view-only import saves its descriptors before it rescans. The wallet's\n // best block is already the tip then, so after a crash it would load without\n-// the older transactions. This records where the rescan starts until it ends.\n-QString PendingImportKey(const std::string& wallet_name)\n+// the older transactions. This records where the rescan starts until it ends,\n+// and whether every descriptor was saved.\n+struct PendingImport {\n+    int64_t start{0};\n+    bool installed{false};\n+};\n+\n+// The marker belongs to the wallet file, not to its name.\n+std::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n {\n-    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_name).toHex()));\n+    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n+    std::error_code error;\n+    const fs::path canonical{fs::weakly_canonical(path, error)};\n+    return fs::PathToString(error ? path : canonical);\n }\n \n-void SetPendingImport(const std::string& wallet_name, std::optional<int64_t> time)\n+QString PendingImportKey(const std::string& wallet_path)\n+{\n+    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n+}\n+\n+void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n-    if (time) {\n-        settings.setValue(PendingImportKey(wallet_name), qlonglong(*time));\n-    } else {\n-        settings.remove(PendingImportKey(wallet_name));\n+    const QString key{PendingImportKey(wallet_path)};\n+    settings.remove(key);\n+    if (pending) {\n+        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n+        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n }\n \n-std::optional<int64_t> PendingImport(const std::string& wallet_name)\n+std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n {\n-    const QVariant time{QSettings{}.value(PendingImportKey(wallet_name))};\n-    return time.isValid() ? std::optional<int64_t>{time.toLongLong()} : std::nullopt;\n+    QSettings settings;\n+    const QString key{PendingImportKey(wallet_path)};\n+    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n+    if (!start.isValid()) return std::nullopt;\n+    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n+}\n+\n+// What the wallet takes as now for an import: the median time of the tip.\n+int64_t ChainNow(interfaces::WalletLoader& loader)\n+{\n+    wallet::WalletContext* context{loader.context()};\n+    int64_t time{0};\n+    if (context && context->chain) {\n+        interfaces::Chain& chain{*context->chain};\n+        if (const std::optional<int> height{chain.getHeight()};\n+            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n+            return time;\n+        }\n+    }\n+    return QDateTime::currentSecsSinceEpoch();\n }\n \n-bool ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control)\n+ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                const std::function<void(int)>& progress)\n {\n+    using Status = ImportRescanResult::Status;\n     wallet::WalletContext* context{node.walletLoader().context()};\n     const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n-    if (!wallet) return false;\n+    if (!wallet) return {Status::Stopped};\n     wallet::WalletRescanReserver reserver{*wallet};\n-    if (!reserver.reserve()) return false;\n-    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return false;\n+    // Another rescan of this wallet is running.\n+    if (!reserver.reserve()) return {Status::Failed};\n+    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n+    // The abort refers to this frame, and Scan can throw.\n+    const auto detach{qScopeGuard([&control] { control.detach(); })};\n+    const auto progress_handler{interfaces::MakeSignalHandler(\n+        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n     int start_height{0};\n     uint256 start_block;\n-    bool done{!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n-                                                               interfaces::FoundBlock().hash(start_block).height(start_height))};\n-    if (!done) {\n-        // Progress is saved, so a later load continues from where this stopped too.\n-        done = wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true).status ==\n-               wallet::ScanResult::SUCCESS;\n+    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n+                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n+        return {Status::Done};\n+    }\n+    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n+    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n+    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n+    ImportRescanResult stopped{Status::Stopped};\n+    int64_t last_time{0};\n+    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n+        stopped.checkpoint = last_time;\n     }\n-    control.detach();\n-    return done;\n+    return stopped;\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -214,8 +262,9 @@ WalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent\n     , m_open_local_path_fn([](const QString& path) {\n         return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n     })\n-    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control) {\n-        return ResumeImport(node, wallet_name, time, control);\n+    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                 const std::function<void(int)>& progress) {\n+        return ResumeImport(node, wallet_name, time, control, progress);\n     })\n {\n     m_empty_wallet->setNode(&m_node);\n@@ -524,8 +573,15 @@ void WalletQmlController::registerWalletModel(WalletQmlModel* wallet_model)\n void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n {\n     const QString name{wallet_model->name()};\n-    const std::optional<int64_t> time{PendingImport(name.toStdString())};\n-    if (!time) return;\n+    if (m_import_rescans.contains(name)) return;\n+    const std::string path{WalletPath(m_node.walletLoader(), name.toStdString())};\n+    const std::optional<PendingImport> pending{ReadPendingImport(path)};\n+    if (!pending) return;\n+    // Rescanning can't add the descriptors that were never saved.\n+    if (!pending->installed) {\n+        wallet_model->setHistoryRecovery(QStringLiteral(\"incomplete\"));\n+        return;\n+    }\n     if (!m_import_rescan_executor) {\n         m_import_rescan_executor = std::make_unique<BackendExecutor>();\n         m_import_rescan_executor->setObjectName(QStringLiteral(\"wallet-import-rescan\"));\n@@ -537,15 +593,43 @@ void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n     }\n     auto control{std::make_shared<RescanControl>()};\n     m_import_rescans[name] = control;\n-    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), time = *time, control] {\n-        // Stays pending when the rescan stops early, so the next load tries again.\n-        if (resume(name, time, *control)) SetPendingImport(name, std::nullopt);\n-    }, [this, name, control] {\n+    wallet_model->setHistoryRecovery(QStringLiteral(\"running\"));\n+    const QPointer<WalletQmlModel> model{wallet_model};\n+    auto progress = [bridge = m_notification_bridge, model](int percent) {\n+        QMetaObject::invokeMethod(bridge.get(), [model, percent] {\n+            if (model) model->setHistoryRecovery(QStringLiteral(\"running\"), percent < 100 ? percent : -1);\n+        }, Qt::QueuedConnection);\n+    };\n+    const auto finished = [this, name, control, model](bool failed) {\n         const auto it{m_import_rescans.find(name)};\n         if (it != m_import_rescans.end() && it->second == control) m_import_rescans.erase(it);\n+        if (model) model->setHistoryRecovery(failed ? QStringLiteral(\"failed\") : QString{});\n+    };\n+    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), path, start = pending->start,\n+                                            control, progress = std::move(progress)] {\n+        using Status = ImportRescanResult::Status;\n+        const ImportRescanResult result{resume(name, start, *control, progress)};\n+        if (result.status == Status::Done) {\n+            SetPendingImport(path, std::nullopt);\n+        } else if (result.status == Status::Stopped && result.checkpoint && *result.checkpoint > start) {\n+            // The next rescan starts a window before the last block read.\n+            SetPendingImport(path, PendingImport{*result.checkpoint, /*installed=*/true});\n+        }\n+        // The marker stays otherwise, so the next load tries again.\n+        return result.status;\n+    }, [finished](ImportRescanResult::Status status) {\n+        finished(status != ImportRescanResult::Status::Done);\n+    }, [finished](std::exception_ptr) {\n+        finished(/*failed=*/true);\n     });\n }\n \n+void WalletQmlController::retryHistoryRecovery(WalletQmlModel* wallet)\n+{\n+    if (!wallet || m_shutting_down || wallet->historyRecovery() != QStringLiteral(\"failed\")) return;\n+    resumeInterruptedImport(wallet);\n+}\n+\n void WalletQmlController::removeWalletModel(WalletQmlModel* wallet_model, bool remove)\n {\n     if (!wallet_model || wallet_model == m_empty_wallet) {\n@@ -676,9 +760,11 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             const auto error = util::ErrorString(wallet);\n             out.error = QString::fromStdString(error.translated.empty() ? error.original : error.translated);\n             if (out.error.isEmpty()) out.error = tr(\"Wallet creation failed.\");\n-        } else if (setup_wallet && !(out.error = setup_wallet(**wallet)).isEmpty()) {\n-            DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n-            SetPendingImport(wallet_name.toStdString(), std::nullopt);\n+        } else if (bool keep_wallet{false}; setup_wallet && !(out.error = setup_wallet(**wallet, keep_wallet)).isEmpty()) {\n+            if (!keep_wallet) {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }\n         } else {\n             out.wallet = std::move(*wallet);\n         }\n@@ -825,9 +911,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n     }\n     const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n-    // An unset timestamp means now.\n-    int64_t rescan_from{QDateTime::currentSecsSinceEpoch()};\n-    for (const auto& request : input.requests) rescan_from = std::min(rescan_from, request.timestamp.value_or(rescan_from));\n     std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n     auto control{std::make_shared<RescanControl>()};\n     m_import_control = control;\n@@ -837,14 +920,20 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                       creation_flags,\n                       WalletLoadAction::Create,\n                       /*report_create_error=*/false,\n-                      [node = &m_node, requests, rescan_from, control, guard = QPointer{this},\n-                       bridge = m_notification_bridge](interfaces::Wallet& wallet) mutable {\n+                      [node = &m_node, requests, control, guard = QPointer{this},\n+                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n-        SetPendingImport(wallet.getWalletName(), rescan_from);\n+        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n+        // Resolved here, so the marker starts where the wallet's rescan does.\n+        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n+        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n         std::vector<wallet::ImportResult> results;\n         {\n-            const auto progress{wallet.handleShowProgress([&wallet, control, guard, bridge](const std::string&, int percent) {\n+            // The rescan starts once every descriptor is saved.\n+            bool installed{false};\n+            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n+                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -856,12 +945,16 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         }\n         control->detach();\n         if (control->cancelled()) return cancelled;\n-        // Shutdown stops the rescan early without an error, which would keep a wallet missing history.\n-        if (node->shutdownRequested()) return WalletQmlController::tr(\"The import was interrupted before it found all transactions.\");\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n         }\n-        SetPendingImport(wallet.getWalletName(), std::nullopt);\n+        // Shutdown stops the rescan early without an error. The next start finishes it.\n+        if (node->shutdownRequested()) {\n+            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+            keep_wallet = true;\n+            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n+        }\n+        SetPendingImport(path, std::nullopt);\n         return QString{};\n     }, [node = &m_node, oldest_dated, chosen_date] {\n         // Checked before the wallet file exists, so another date can be tried with the same name.\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 280,
    "evidence_id": "63ef6ff73fdf46478eed24f5bf088ed4",
    "finding_id": "finding:11",
    "kind": "new_source",
    "line": 131,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "    bool installed{false};\n};\n\n// The marker belongs to the wallet file, not to its name.\nstd::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n{\n    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n    std::error_code error;\n    const fs::path canonical{fs::weakly_canonical(path, error)};\n    return fs::PathToString(error ? path : canonical);\n}\n\nQString PendingImportKey(const std::string& wallet_path)\n{\n    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n}\n\nvoid SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n{\n    QSettings settings;\n    const QString key{PendingImportKey(wallet_path)};\n    settings.remove(key);\n    if (pending) {\n        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n    }\n    settings.sync();\n}\n\nstd::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n{\n    QSettings settings;\n    const QString key{PendingImportKey(wallet_path)};\n    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n    if (!start.isValid()) return std::nullopt;\n    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n}\n\n// What the wallet takes as now for an import: the median time of the tip.\nint64_t ChainNow(interfaces::WalletLoader& loader)\n{\n    wallet::WalletContext* context{loader.context()};\n    int64_t time{0};\n    if (context && context->chain) {\n        interfaces::Chain& chain{*context->chain};\n        if (const std::optional<int> height{chain.getHeight()};\n            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n            return time;\n        }\n    }\n    return QDateTime::currentSecsSinceEpoch();\n}\n\nImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n                                const std::function<void(int)>& progress)\n{\n    using Status = ImportRescanResult::Status;\n    wallet::WalletContext* context{node.walletLoader().context()};\n    const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n    if (!wallet) return {Status::Stopped};\n    wallet::WalletRescanReserver reserver{*wallet};\n    // Another rescan of this wallet is running.\n    if (!reserver.reserve()) return {Status::Failed};\n    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n    // The abort refers to this frame, and Scan can throw.\n    const auto detach{qScopeGuard([&control] { control.detach(); })};\n    const auto progress_handler{interfaces::MakeSignalHandler(\n        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n    int start_height{0};\n    uint256 start_block;\n    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n        return {Status::Done};\n    }\n    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n    ImportRescanResult stopped{Status::Stopped};\n    int64_t last_time{0};\n    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n        stopped.checkpoint = last_time;\n    }\n    return stopped;\n}\n\nQString ImportErrorText(const wallet::ImportError& error)\n{\n    const bilingual_str& message{error.wallet_error.message};\n    return QString::fromStdString(message.translated.empty() ? message.original : message.translated);\n}\n} // namespace\n\nbool RescanControl::attach(std::function<void()> abort)\n{\n    const std::lock_guard lock{m_mutex};\n    if (m_cancelled) return false;\n    m_abort = std::move(abort);\n    return true;\n}\n\nvoid RescanControl::detach()\n{\n    const std::lock_guard lock{m_mutex};\n    m_abort = nullptr;\n}\n\nvoid RescanControl::cancel()\n{\n    const std::lock_guard lock{m_mutex};\n    m_cancelled = true;\n    if (m_abort) m_abort();\n}\n\nbool RescanControl::cancelled() const\n{\n    const std::lock_guard lock{m_mutex};\n    return m_cancelled;\n}\n\nWalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent)\n    : QObject(parent)\n    , m_node(node)\n    , m_empty_wallet(new WalletQmlModel(&node, this))\n    , m_selected_wallet(m_empty_wallet)\n    , m_wallet_command_executor(std::make_shared<BackendExecutor>())\n    , m_load_notifications(std::make_shared<WalletLoadNotifications>())\n    , m_notification_bridge(new QObject, [](QObject* bridge) {\n        if (QThread::currentThread() == bridge->thread()) delete bridge;\n        else bridge->deleteLater();\n    })\n    , m_open_local_path_fn([](const QString& path) {\n        return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n    })\n    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n                                 const std::function<void(int)>& progress) {\n        return ResumeImport(node, wallet_name, time, control, progress);\n    })\n{\n    m_empty_wallet->setNode(&m_node);\n    m_wallet_command_executor->setObjectName(QStringLiteral(\"wallet-commands\"));\n    connect(m_wallet_command_executor.get(), &BackendExecutor::drained, this, [this] {\n        m_controller_drained = true;\n        checkShutdownFinished();\n    });\n\n}\n\nWalletQmlController::~WalletQmlController()\n{",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1144Recovery cannot distinguish partial installation from a pending scanqml/walletqmlcontroller.cppaddressed
Assessment

The pending marker now records whether descriptor installation completed. Recovery detects an uninstalled marker and reports an incomplete import instead of rescanning and clearing it as though installation had completed.

path_diff: qml/walletqmlcontroller.cpp; new_source: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "26691d54ef574b61948b7acafc2009a6",
    "finding_id": "finding:10",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 452a87cf64..81317bf10e 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -13,6 +13,7 @@\n #include <common/args.h>\n #include <common/settings.h>\n #include <interfaces/chain.h>\n+#include <interfaces/handler.h>\n #include <interfaces/node.h>\n #include <interfaces/wallet.h>\n #include <support/allocators/secure.h>\n@@ -45,6 +46,7 @@\n #include <QMetaObject>\n #include <QPointer>\n #include <QRegularExpression>\n+#include <QScopeGuard>\n #include <QSettings>\n #include <QStringList>\n #include <QTimer>\n@@ -122,48 +124,94 @@ void DiscardCreatedWallet(interfaces::WalletLoader& loader, std::unique_ptr<inte\n \n // A view-only import saves its descriptors before it rescans. The wallet's\n // best block is already the tip then, so after a crash it would load without\n-// the older transactions. This records where the rescan starts until it ends.\n-QString PendingImportKey(const std::string& wallet_name)\n+// the older transactions. This records where the rescan starts until it ends,\n+// and whether every descriptor was saved.\n+struct PendingImport {\n+    int64_t start{0};\n+    bool installed{false};\n+};\n+\n+// The marker belongs to the wallet file, not to its name.\n+std::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n {\n-    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_name).toHex()));\n+    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n+    std::error_code error;\n+    const fs::path canonical{fs::weakly_canonical(path, error)};\n+    return fs::PathToString(error ? path : canonical);\n }\n \n-void SetPendingImport(const std::string& wallet_name, std::optional<int64_t> time)\n+QString PendingImportKey(const std::string& wallet_path)\n+{\n+    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n+}\n+\n+void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n-    if (time) {\n-        settings.setValue(PendingImportKey(wallet_name), qlonglong(*time));\n-    } else {\n-        settings.remove(PendingImportKey(wallet_name));\n+    const QString key{PendingImportKey(wallet_path)};\n+    settings.remove(key);\n+    if (pending) {\n+        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n+        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n }\n \n-std::optional<int64_t> PendingImport(const std::string& wallet_name)\n+std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n {\n-    const QVariant time{QSettings{}.value(PendingImportKey(wallet_name))};\n-    return time.isValid() ? std::optional<int64_t>{time.toLongLong()} : std::nullopt;\n+    QSettings settings;\n+    const QString key{PendingImportKey(wallet_path)};\n+    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n+    if (!start.isValid()) return std::nullopt;\n+    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n+}\n+\n+// What the wallet takes as now for an import: the median time of the tip.\n+int64_t ChainNow(interfaces::WalletLoader& loader)\n+{\n+    wallet::WalletContext* context{loader.context()};\n+    int64_t time{0};\n+    if (context && context->chain) {\n+        interfaces::Chain& chain{*context->chain};\n+        if (const std::optional<int> height{chain.getHeight()};\n+            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n+            return time;\n+        }\n+    }\n+    return QDateTime::currentSecsSinceEpoch();\n }\n \n-bool ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control)\n+ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                const std::function<void(int)>& progress)\n {\n+    using Status = ImportRescanResult::Status;\n     wallet::WalletContext* context{node.walletLoader().context()};\n     const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n-    if (!wallet) return false;\n+    if (!wallet) return {Status::Stopped};\n     wallet::WalletRescanReserver reserver{*wallet};\n-    if (!reserver.reserve()) return false;\n-    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return false;\n+    // Another rescan of this wallet is running.\n+    if (!reserver.reserve()) return {Status::Failed};\n+    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n+    // The abort refers to this frame, and Scan can throw.\n+    const auto detach{qScopeGuard([&control] { control.detach(); })};\n+    const auto progress_handler{interfaces::MakeSignalHandler(\n+        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n     int start_height{0};\n     uint256 start_block;\n-    bool done{!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n-                                                               interfaces::FoundBlock().hash(start_block).height(start_height))};\n-    if (!done) {\n-        // Progress is saved, so a later load continues from where this stopped too.\n-        done = wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true).status ==\n-               wallet::ScanResult::SUCCESS;\n+    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n+                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n+        return {Status::Done};\n+    }\n+    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n+    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n+    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n+    ImportRescanResult stopped{Status::Stopped};\n+    int64_t last_time{0};\n+    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n+        stopped.checkpoint = last_time;\n     }\n-    control.detach();\n-    return done;\n+    return stopped;\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -214,8 +262,9 @@ WalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent\n     , m_open_local_path_fn([](const QString& path) {\n         return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n     })\n-    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control) {\n-        return ResumeImport(node, wallet_name, time, control);\n+    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                 const std::function<void(int)>& progress) {\n+        return ResumeImport(node, wallet_name, time, control, progress);\n     })\n {\n     m_empty_wallet->setNode(&m_node);\n@@ -524,8 +573,15 @@ void WalletQmlController::registerWalletModel(WalletQmlModel* wallet_model)\n void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n {\n     const QString name{wallet_model->name()};\n-    const std::optional<int64_t> time{PendingImport(name.toStdString())};\n-    if (!time) return;\n+    if (m_import_rescans.contains(name)) return;\n+    const std::string path{WalletPath(m_node.walletLoader(), name.toStdString())};\n+    const std::optional<PendingImport> pending{ReadPendingImport(path)};\n+    if (!pending) return;\n+    // Rescanning can't add the descriptors that were never saved.\n+    if (!pending->installed) {\n+        wallet_model->setHistoryRecovery(QStringLiteral(\"incomplete\"));\n+        return;\n+    }\n     if (!m_import_rescan_executor) {\n         m_import_rescan_executor = std::make_unique<BackendExecutor>();\n         m_import_rescan_executor->setObjectName(QStringLiteral(\"wallet-import-rescan\"));\n@@ -537,15 +593,43 @@ void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n     }\n     auto control{std::make_shared<RescanControl>()};\n     m_import_rescans[name] = control;\n-    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), time = *time, control] {\n-        // Stays pending when the rescan stops early, so the next load tries again.\n-        if (resume(name, time, *control)) SetPendingImport(name, std::nullopt);\n-    }, [this, name, control] {\n+    wallet_model->setHistoryRecovery(QStringLiteral(\"running\"));\n+    const QPointer<WalletQmlModel> model{wallet_model};\n+    auto progress = [bridge = m_notification_bridge, model](int percent) {\n+        QMetaObject::invokeMethod(bridge.get(), [model, percent] {\n+            if (model) model->setHistoryRecovery(QStringLiteral(\"running\"), percent < 100 ? percent : -1);\n+        }, Qt::QueuedConnection);\n+    };\n+    const auto finished = [this, name, control, model](bool failed) {\n         const auto it{m_import_rescans.find(name)};\n         if (it != m_import_rescans.end() && it->second == control) m_import_rescans.erase(it);\n+        if (model) model->setHistoryRecovery(failed ? QStringLiteral(\"failed\") : QString{});\n+    };\n+    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), path, start = pending->start,\n+                                            control, progress = std::move(progress)] {\n+        using Status = ImportRescanResult::Status;\n+        const ImportRescanResult result{resume(name, start, *control, progress)};\n+        if (result.status == Status::Done) {\n+            SetPendingImport(path, std::nullopt);\n+        } else if (result.status == Status::Stopped && result.checkpoint && *result.checkpoint > start) {\n+            // The next rescan starts a window before the last block read.\n+            SetPendingImport(path, PendingImport{*result.checkpoint, /*installed=*/true});\n+        }\n+        // The marker stays otherwise, so the next load tries again.\n+        return result.status;\n+    }, [finished](ImportRescanResult::Status status) {\n+        finished(status != ImportRescanResult::Status::Done);\n+    }, [finished](std::exception_ptr) {\n+        finished(/*failed=*/true);\n     });\n }\n \n+void WalletQmlController::retryHistoryRecovery(WalletQmlModel* wallet)\n+{\n+    if (!wallet || m_shutting_down || wallet->historyRecovery() != QStringLiteral(\"failed\")) return;\n+    resumeInterruptedImport(wallet);\n+}\n+\n void WalletQmlController::removeWalletModel(WalletQmlModel* wallet_model, bool remove)\n {\n     if (!wallet_model || wallet_model == m_empty_wallet) {\n@@ -676,9 +760,11 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             const auto error = util::ErrorString(wallet);\n             out.error = QString::fromStdString(error.translated.empty() ? error.original : error.translated);\n             if (out.error.isEmpty()) out.error = tr(\"Wallet creation failed.\");\n-        } else if (setup_wallet && !(out.error = setup_wallet(**wallet)).isEmpty()) {\n-            DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n-            SetPendingImport(wallet_name.toStdString(), std::nullopt);\n+        } else if (bool keep_wallet{false}; setup_wallet && !(out.error = setup_wallet(**wallet, keep_wallet)).isEmpty()) {\n+            if (!keep_wallet) {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }\n         } else {\n             out.wallet = std::move(*wallet);\n         }\n@@ -825,9 +911,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n     }\n     const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n-    // An unset timestamp means now.\n-    int64_t rescan_from{QDateTime::currentSecsSinceEpoch()};\n-    for (const auto& request : input.requests) rescan_from = std::min(rescan_from, request.timestamp.value_or(rescan_from));\n     std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n     auto control{std::make_shared<RescanControl>()};\n     m_import_control = control;\n@@ -837,14 +920,20 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                       creation_flags,\n                       WalletLoadAction::Create,\n                       /*report_create_error=*/false,\n-                      [node = &m_node, requests, rescan_from, control, guard = QPointer{this},\n-                       bridge = m_notification_bridge](interfaces::Wallet& wallet) mutable {\n+                      [node = &m_node, requests, control, guard = QPointer{this},\n+                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n-        SetPendingImport(wallet.getWalletName(), rescan_from);\n+        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n+        // Resolved here, so the marker starts where the wallet's rescan does.\n+        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n+        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n         std::vector<wallet::ImportResult> results;\n         {\n-            const auto progress{wallet.handleShowProgress([&wallet, control, guard, bridge](const std::string&, int percent) {\n+            // The rescan starts once every descriptor is saved.\n+            bool installed{false};\n+            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n+                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -856,12 +945,16 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         }\n         control->detach();\n         if (control->cancelled()) return cancelled;\n-        // Shutdown stops the rescan early without an error, which would keep a wallet missing history.\n-        if (node->shutdownRequested()) return WalletQmlController::tr(\"The import was interrupted before it found all transactions.\");\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n         }\n-        SetPendingImport(wallet.getWalletName(), std::nullopt);\n+        // Shutdown stops the rescan early without an error. The next start finishes it.\n+        if (node->shutdownRequested()) {\n+            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+            keep_wallet = true;\n+            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n+        }\n+        SetPendingImport(path, std::nullopt);\n         return QString{};\n     }, [node = &m_node, oldest_dated, chosen_date] {\n         // Checked before the wallet file exists, so another date can be tried with the same name.\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 963,
    "evidence_id": "34b5720791f547dfb20eece793234227",
    "finding_id": "finding:10",
    "kind": "new_source",
    "line": 814,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "                      wallet::WALLET_FLAG_DESCRIPTORS,\n                      WalletLoadAction::Create,\n                      /*report_create_error=*/true);\n}\n\nbool WalletQmlController::createExternalSignerWallet(const QString& name)\n{\n    clearWalletLoadStatus();\n    clearWalletMigrationStatus();\n    if (!m_initialized) {\n        setWalletLoadError(tr(\"Wallets are still loading. Try again in a moment.\"));\n        return false;\n    }\n\n    const QString wallet_name = name.trimmed();\n    const QString name_error = walletNameAvailabilityError(wallet_name);\n    if (!name_error.isEmpty()) {\n        setWalletLoadError(name_error);\n        return false;\n    }\n\n    refreshExternalSignerStatus();\n    if (!m_external_signer_path_configured) {\n        setWalletLoadError(tr(\"Set an external signer path in Wallet settings first.\"));\n        return false;\n    }\n    if (!m_external_signer_error.isEmpty()) {\n        setWalletLoadError(m_external_signer_error);\n        return false;\n    }\n    if (m_external_signer_count == 0) {\n        setWalletLoadError(tr(\"Connect an external signer and try again.\"));\n        return false;\n    }\n    if (m_external_signer_count > 1) {\n        setWalletLoadError(tr(\"More than one external signer was found. Connect only one device and try again.\"));\n        return false;\n    }\n\n    constexpr uint64_t flags = wallet::WALLET_FLAG_DESCRIPTORS |\n        wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS |\n        wallet::WALLET_FLAG_EXTERNAL_SIGNER;\n    createWalletAsync(wallet_name,\n                      SecureString{},\n                      flags,\n                      WalletLoadAction::Load,\n                      /*report_create_error=*/false);\n    return true;\n}\n\nvoid WalletQmlController::createWatchOnlyWallet(const QString& name, const QString& import_text, qint64 birth_time,\n                                                const QString& address_type)\n{\n    if (m_wallet_load_in_progress) {\n        return;\n    }\n    clearWalletLoadStatus();\n    clearWalletMigrationStatus();\n    if (!m_initialized) {\n        setWalletLoadError(tr(\"Wallets are still loading. Try again in a moment.\"));\n        return;\n    }\n\n    ViewOnlyImport input{ParseViewOnlyImport(import_text, address_type)};\n    if (input.kind == ViewOnlyImport::Kind::Empty) {\n        setWalletLoadError(tr(\"Enter descriptors, or an extended public key (xpub).\"));\n        return;\n    }\n    if (!input.error.isEmpty()) {\n        setWalletLoadError(input.error);\n        return;\n    }\n    if (input.requests.empty()) {\n        setWalletLoadError(tr(\"Choose the address type of this key.\"));\n        return;\n    }\n    if (!input.undated.empty()) {\n        if (birth_time < 0) {\n            setWalletLoadError(tr(\"Choose when this wallet was created.\"));\n            return;\n        }\n        for (const size_t index : input.undated) input.requests[index].timestamp = birth_time;\n    }\n\n    const QString name_error = walletNameAvailabilityError(name);\n    if (!name_error.isEmpty()) {\n        setWalletLoadError(name_error);\n        return;\n    }\n\n    const uint64_t creation_flags = wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS |\n                                    wallet::WALLET_FLAG_DESCRIPTORS |\n                                    wallet::WALLET_FLAG_BLANK_WALLET;\n    // Only undated requests take the chosen date, so a dated one can need pruned blocks whatever the date.\n    std::optional<int64_t> oldest_dated;\n    for (size_t i = 0; i < input.requests.size(); ++i) {\n        const std::optional<int64_t>& time{input.requests[i].timestamp};\n        if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n    }\n    const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n    std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n    auto control{std::make_shared<RescanControl>()};\n    m_import_control = control;\n    setImportProgress(-1);\n    createWalletAsync(name.trimmed(),\n                      SecureString{},\n                      creation_flags,\n                      WalletLoadAction::Create,\n                      /*report_create_error=*/false,\n                      [node = &m_node, requests, control, guard = QPointer{this},\n                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n        const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n        if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n        // Resolved here, so the marker starts where the wallet's rescan does.\n        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n        std::vector<wallet::ImportResult> results;\n        {\n            // The rescan starts once every descriptor is saved.\n            bool installed{false};\n            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n                // Starting a rescan clears an earlier abort.\n                if (control->cancelled()) wallet.abortRescan();\n                QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n                    if (guard) guard->setImportProgress(percent < 100 ? percent : -1);\n                }, Qt::QueuedConnection);\n            })};\n            // Imports the descriptors, then rescans from the oldest timestamp.\n            results = wallet.importDescriptors(requests);\n        }\n        control->detach();\n        if (control->cancelled()) return cancelled;\n        for (const wallet::ImportResult& result : results) {\n            if (result.has_error()) return ImportErrorText(*result.error);\n        }\n        // Shutdown stops the rescan early without an error. The next start finishes it.\n        if (node->shutdownRequested()) {\n            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n            keep_wallet = true;\n            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n        }\n        SetPendingImport(path, std::nullopt);\n        return QString{};\n    }, [node = &m_node, oldest_dated, chosen_date] {\n        // Checked before the wallet file exists, so another date can be tried with the same name.\n        wallet::WalletContext* context{node->walletLoader().context()};\n        if (!context || !context->chain) return QString{};\n        if (ScanBlocksPruned(*context->chain, oldest_dated)) {",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1144A recovery-scan exception leaves a dangling abort callbackqml/walletqmlcontroller.cppaddressed
Assessment

A scope guard now detaches the abort callback immediately after successful attachment, including on exceptions. The recovery executor also has an exception completion handler that removes the control while leaving the pending marker intact.

path_diff: qml/walletqmlcontroller.cpp; new_source: qml/walletqmlcontroller.cpp

[
  {
    "evidence_id": "79492e8593f242b9a0a98981f79825e4",
    "finding_id": "finding:1",
    "kind": "path_diff",
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "diff --git a/qml/walletqmlcontroller.cpp b/qml/walletqmlcontroller.cpp\nindex 452a87cf64..81317bf10e 100644\n--- a/qml/walletqmlcontroller.cpp\n+++ b/qml/walletqmlcontroller.cpp\n@@ -13,6 +13,7 @@\n #include <common/args.h>\n #include <common/settings.h>\n #include <interfaces/chain.h>\n+#include <interfaces/handler.h>\n #include <interfaces/node.h>\n #include <interfaces/wallet.h>\n #include <support/allocators/secure.h>\n@@ -45,6 +46,7 @@\n #include <QMetaObject>\n #include <QPointer>\n #include <QRegularExpression>\n+#include <QScopeGuard>\n #include <QSettings>\n #include <QStringList>\n #include <QTimer>\n@@ -122,48 +124,94 @@ void DiscardCreatedWallet(interfaces::WalletLoader& loader, std::unique_ptr<inte\n \n // A view-only import saves its descriptors before it rescans. The wallet's\n // best block is already the tip then, so after a crash it would load without\n-// the older transactions. This records where the rescan starts until it ends.\n-QString PendingImportKey(const std::string& wallet_name)\n+// the older transactions. This records where the rescan starts until it ends,\n+// and whether every descriptor was saved.\n+struct PendingImport {\n+    int64_t start{0};\n+    bool installed{false};\n+};\n+\n+// The marker belongs to the wallet file, not to its name.\n+std::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n {\n-    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_name).toHex()));\n+    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n+    std::error_code error;\n+    const fs::path canonical{fs::weakly_canonical(path, error)};\n+    return fs::PathToString(error ? path : canonical);\n }\n \n-void SetPendingImport(const std::string& wallet_name, std::optional<int64_t> time)\n+QString PendingImportKey(const std::string& wallet_path)\n+{\n+    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n+}\n+\n+void SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n {\n     QSettings settings;\n-    if (time) {\n-        settings.setValue(PendingImportKey(wallet_name), qlonglong(*time));\n-    } else {\n-        settings.remove(PendingImportKey(wallet_name));\n+    const QString key{PendingImportKey(wallet_path)};\n+    settings.remove(key);\n+    if (pending) {\n+        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n+        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n     }\n     settings.sync();\n }\n \n-std::optional<int64_t> PendingImport(const std::string& wallet_name)\n+std::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n {\n-    const QVariant time{QSettings{}.value(PendingImportKey(wallet_name))};\n-    return time.isValid() ? std::optional<int64_t>{time.toLongLong()} : std::nullopt;\n+    QSettings settings;\n+    const QString key{PendingImportKey(wallet_path)};\n+    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n+    if (!start.isValid()) return std::nullopt;\n+    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n+}\n+\n+// What the wallet takes as now for an import: the median time of the tip.\n+int64_t ChainNow(interfaces::WalletLoader& loader)\n+{\n+    wallet::WalletContext* context{loader.context()};\n+    int64_t time{0};\n+    if (context && context->chain) {\n+        interfaces::Chain& chain{*context->chain};\n+        if (const std::optional<int> height{chain.getHeight()};\n+            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n+            return time;\n+        }\n+    }\n+    return QDateTime::currentSecsSinceEpoch();\n }\n \n-bool ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control)\n+ImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                const std::function<void(int)>& progress)\n {\n+    using Status = ImportRescanResult::Status;\n     wallet::WalletContext* context{node.walletLoader().context()};\n     const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n-    if (!wallet) return false;\n+    if (!wallet) return {Status::Stopped};\n     wallet::WalletRescanReserver reserver{*wallet};\n-    if (!reserver.reserve()) return false;\n-    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return false;\n+    // Another rescan of this wallet is running.\n+    if (!reserver.reserve()) return {Status::Failed};\n+    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n+    // The abort refers to this frame, and Scan can throw.\n+    const auto detach{qScopeGuard([&control] { control.detach(); })};\n+    const auto progress_handler{interfaces::MakeSignalHandler(\n+        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n     int start_height{0};\n     uint256 start_block;\n-    bool done{!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n-                                                               interfaces::FoundBlock().hash(start_block).height(start_height))};\n-    if (!done) {\n-        // Progress is saved, so a later load continues from where this stopped too.\n-        done = wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true).status ==\n-               wallet::ScanResult::SUCCESS;\n+    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n+                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n+        return {Status::Done};\n+    }\n+    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n+    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n+    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n+    ImportRescanResult stopped{Status::Stopped};\n+    int64_t last_time{0};\n+    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n+        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n+        stopped.checkpoint = last_time;\n     }\n-    control.detach();\n-    return done;\n+    return stopped;\n }\n \n QString ImportErrorText(const wallet::ImportError& error)\n@@ -214,8 +262,9 @@ WalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent\n     , m_open_local_path_fn([](const QString& path) {\n         return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n     })\n-    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control) {\n-        return ResumeImport(node, wallet_name, time, control);\n+    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n+                                 const std::function<void(int)>& progress) {\n+        return ResumeImport(node, wallet_name, time, control, progress);\n     })\n {\n     m_empty_wallet->setNode(&m_node);\n@@ -524,8 +573,15 @@ void WalletQmlController::registerWalletModel(WalletQmlModel* wallet_model)\n void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n {\n     const QString name{wallet_model->name()};\n-    const std::optional<int64_t> time{PendingImport(name.toStdString())};\n-    if (!time) return;\n+    if (m_import_rescans.contains(name)) return;\n+    const std::string path{WalletPath(m_node.walletLoader(), name.toStdString())};\n+    const std::optional<PendingImport> pending{ReadPendingImport(path)};\n+    if (!pending) return;\n+    // Rescanning can't add the descriptors that were never saved.\n+    if (!pending->installed) {\n+        wallet_model->setHistoryRecovery(QStringLiteral(\"incomplete\"));\n+        return;\n+    }\n     if (!m_import_rescan_executor) {\n         m_import_rescan_executor = std::make_unique<BackendExecutor>();\n         m_import_rescan_executor->setObjectName(QStringLiteral(\"wallet-import-rescan\"));\n@@ -537,15 +593,43 @@ void WalletQmlController::resumeInterruptedImport(WalletQmlModel* wallet_model)\n     }\n     auto control{std::make_shared<RescanControl>()};\n     m_import_rescans[name] = control;\n-    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), time = *time, control] {\n-        // Stays pending when the rescan stops early, so the next load tries again.\n-        if (resume(name, time, *control)) SetPendingImport(name, std::nullopt);\n-    }, [this, name, control] {\n+    wallet_model->setHistoryRecovery(QStringLiteral(\"running\"));\n+    const QPointer<WalletQmlModel> model{wallet_model};\n+    auto progress = [bridge = m_notification_bridge, model](int percent) {\n+        QMetaObject::invokeMethod(bridge.get(), [model, percent] {\n+            if (model) model->setHistoryRecovery(QStringLiteral(\"running\"), percent < 100 ? percent : -1);\n+        }, Qt::QueuedConnection);\n+    };\n+    const auto finished = [this, name, control, model](bool failed) {\n         const auto it{m_import_rescans.find(name)};\n         if (it != m_import_rescans.end() && it->second == control) m_import_rescans.erase(it);\n+        if (model) model->setHistoryRecovery(failed ? QStringLiteral(\"failed\") : QString{});\n+    };\n+    m_import_rescan_executor->submit(this, [resume = m_resume_import_fn, name = name.toStdString(), path, start = pending->start,\n+                                            control, progress = std::move(progress)] {\n+        using Status = ImportRescanResult::Status;\n+        const ImportRescanResult result{resume(name, start, *control, progress)};\n+        if (result.status == Status::Done) {\n+            SetPendingImport(path, std::nullopt);\n+        } else if (result.status == Status::Stopped && result.checkpoint && *result.checkpoint > start) {\n+            // The next rescan starts a window before the last block read.\n+            SetPendingImport(path, PendingImport{*result.checkpoint, /*installed=*/true});\n+        }\n+        // The marker stays otherwise, so the next load tries again.\n+        return result.status;\n+    }, [finished](ImportRescanResult::Status status) {\n+        finished(status != ImportRescanResult::Status::Done);\n+    }, [finished](std::exception_ptr) {\n+        finished(/*failed=*/true);\n     });\n }\n \n+void WalletQmlController::retryHistoryRecovery(WalletQmlModel* wallet)\n+{\n+    if (!wallet || m_shutting_down || wallet->historyRecovery() != QStringLiteral(\"failed\")) return;\n+    resumeInterruptedImport(wallet);\n+}\n+\n void WalletQmlController::removeWalletModel(WalletQmlModel* wallet_model, bool remove)\n {\n     if (!wallet_model || wallet_model == m_empty_wallet) {\n@@ -676,9 +760,11 @@ void WalletQmlController::createWalletAsync(const QString& name,\n             const auto error = util::ErrorString(wallet);\n             out.error = QString::fromStdString(error.translated.empty() ? error.original : error.translated);\n             if (out.error.isEmpty()) out.error = tr(\"Wallet creation failed.\");\n-        } else if (setup_wallet && !(out.error = setup_wallet(**wallet)).isEmpty()) {\n-            DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n-            SetPendingImport(wallet_name.toStdString(), std::nullopt);\n+        } else if (bool keep_wallet{false}; setup_wallet && !(out.error = setup_wallet(**wallet, keep_wallet)).isEmpty()) {\n+            if (!keep_wallet) {\n+                DiscardCreatedWallet(node->walletLoader(), std::move(*wallet));\n+                SetPendingImport(WalletPath(node->walletLoader(), wallet_name.toStdString()), std::nullopt);\n+            }\n         } else {\n             out.wallet = std::move(*wallet);\n         }\n@@ -825,9 +911,6 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         if (time && std::ranges::find(input.undated, i) == input.undated.end()) oldest_dated = std::min(oldest_dated.value_or(*time), *time);\n     }\n     const std::optional<int64_t> chosen_date{input.undated.empty() ? std::nullopt : std::optional{birth_time}};\n-    // An unset timestamp means now.\n-    int64_t rescan_from{QDateTime::currentSecsSinceEpoch()};\n-    for (const auto& request : input.requests) rescan_from = std::min(rescan_from, request.timestamp.value_or(rescan_from));\n     std::vector<wallet::ImportDescriptorRequest> requests{std::move(input.requests)};\n     auto control{std::make_shared<RescanControl>()};\n     m_import_control = control;\n@@ -837,14 +920,20 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n                       creation_flags,\n                       WalletLoadAction::Create,\n                       /*report_create_error=*/false,\n-                      [node = &m_node, requests, rescan_from, control, guard = QPointer{this},\n-                       bridge = m_notification_bridge](interfaces::Wallet& wallet) mutable {\n+                      [node = &m_node, requests, control, guard = QPointer{this},\n+                       bridge = m_notification_bridge](interfaces::Wallet& wallet, bool& keep_wallet) mutable {\n         const QString cancelled{WalletQmlController::tr(\"The import was cancelled, and its wallet was deleted.\")};\n         if (!control->attach([&wallet] { wallet.abortRescan(); })) return cancelled;\n-        SetPendingImport(wallet.getWalletName(), rescan_from);\n+        const std::string path{WalletPath(node->walletLoader(), wallet.getWalletName())};\n+        // Resolved here, so the marker starts where the wallet's rescan does.\n+        const int64_t start{ResolveImportTimes(requests, ChainNow(node->walletLoader()))};\n+        SetPendingImport(path, PendingImport{start, /*installed=*/false});\n         std::vector<wallet::ImportResult> results;\n         {\n-            const auto progress{wallet.handleShowProgress([&wallet, control, guard, bridge](const std::string&, int percent) {\n+            // The rescan starts once every descriptor is saved.\n+            bool installed{false};\n+            const auto progress{wallet.handleShowProgress([&, control, guard, bridge](const std::string&, int percent) {\n+                if (!std::exchange(installed, true)) SetPendingImport(path, PendingImport{start, /*installed=*/true});\n                 // Starting a rescan clears an earlier abort.\n                 if (control->cancelled()) wallet.abortRescan();\n                 QMetaObject::invokeMethod(bridge.get(), [guard, percent] {\n@@ -856,12 +945,16 @@ void WalletQmlController::createWatchOnlyWallet(const QString& name, const QStri\n         }\n         control->detach();\n         if (control->cancelled()) return cancelled;\n-        // Shutdown stops the rescan early without an error, which would keep a wallet missing history.\n-        if (node->shutdownRequested()) return WalletQmlController::tr(\"The import was interrupted before it found all transactions.\");\n         for (const wallet::ImportResult& result : results) {\n             if (result.has_error()) return ImportErrorText(*result.error);\n         }\n-        SetPendingImport(wallet.getWalletName(), std::nullopt);\n+        // Shutdown stops the rescan early without an error. The next start finishes it.\n+        if (node->shutdownRequested()) {\n+            SetPendingImport(path, PendingImport{start, /*installed=*/true});\n+            keep_wallet = true;\n+            return WalletQmlController::tr(\"The import will finish the next time the app starts.\");\n+        }\n+        SetPendingImport(path, std::nullopt);\n         return QString{};\n     }, [node = &m_node, oldest_dated, chosen_date] {\n         // Checked before the wallet file exists, so another date can be tried with the same name.\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 274,
    "evidence_id": "5591d4253d864b41810327f26952e96d",
    "finding_id": "finding:1",
    "kind": "new_source",
    "line": 125,
    "new_head": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "old_head": "c6ff067c1dff9e21a9623ca4347013b5ec600481",
    "path": "qml/walletqmlcontroller.cpp",
    "revision": "60c9d57773fbcffdd5f6355d1a695f07e8d51939",
    "source_generation": 3,
    "source_job_id": 3100,
    "text": "// A view-only import saves its descriptors before it rescans. The wallet's\n// best block is already the tip then, so after a crash it would load without\n// the older transactions. This records where the rescan starts until it ends,\n// and whether every descriptor was saved.\nstruct PendingImport {\n    int64_t start{0};\n    bool installed{false};\n};\n\n// The marker belongs to the wallet file, not to its name.\nstd::string WalletPath(interfaces::WalletLoader& loader, const std::string& wallet_name)\n{\n    const fs::path path{fs::PathFromString(loader.getWalletDir()) / fs::PathFromString(wallet_name)};\n    std::error_code error;\n    const fs::path canonical{fs::weakly_canonical(path, error)};\n    return fs::PathToString(error ? path : canonical);\n}\n\nQString PendingImportKey(const std::string& wallet_path)\n{\n    return QStringLiteral(\"pendingViewOnlyImports/%1\").arg(QString::fromLatin1(QByteArray::fromStdString(wallet_path).toHex()));\n}\n\nvoid SetPendingImport(const std::string& wallet_path, std::optional<PendingImport> pending)\n{\n    QSettings settings;\n    const QString key{PendingImportKey(wallet_path)};\n    settings.remove(key);\n    if (pending) {\n        settings.setValue(key + QStringLiteral(\"/start\"), qlonglong(pending->start));\n        settings.setValue(key + QStringLiteral(\"/installed\"), pending->installed);\n    }\n    settings.sync();\n}\n\nstd::optional<PendingImport> ReadPendingImport(const std::string& wallet_path)\n{\n    QSettings settings;\n    const QString key{PendingImportKey(wallet_path)};\n    const QVariant start{settings.value(key + QStringLiteral(\"/start\"))};\n    if (!start.isValid()) return std::nullopt;\n    return PendingImport{start.toLongLong(), settings.value(key + QStringLiteral(\"/installed\")).toBool()};\n}\n\n// What the wallet takes as now for an import: the median time of the tip.\nint64_t ChainNow(interfaces::WalletLoader& loader)\n{\n    wallet::WalletContext* context{loader.context()};\n    int64_t time{0};\n    if (context && context->chain) {\n        interfaces::Chain& chain{*context->chain};\n        if (const std::optional<int> height{chain.getHeight()};\n            height && chain.findBlock(chain.getBlockHash(*height), interfaces::FoundBlock().mtpTime(time))) {\n            return time;\n        }\n    }\n    return QDateTime::currentSecsSinceEpoch();\n}\n\nImportRescanResult ResumeImport(interfaces::Node& node, const std::string& wallet_name, int64_t time, RescanControl& control,\n                                const std::function<void(int)>& progress)\n{\n    using Status = ImportRescanResult::Status;\n    wallet::WalletContext* context{node.walletLoader().context()};\n    const std::shared_ptr<wallet::CWallet> wallet{context ? wallet::GetWallet(*context, wallet_name) : nullptr};\n    if (!wallet) return {Status::Stopped};\n    wallet::WalletRescanReserver reserver{*wallet};\n    // Another rescan of this wallet is running.\n    if (!reserver.reserve()) return {Status::Failed};\n    if (!control.attach([&wallet] { wallet->Scanner().Abort(); })) return {Status::Stopped};\n    // The abort refers to this frame, and Scan can throw.\n    const auto detach{qScopeGuard([&control] { control.detach(); })};\n    const auto progress_handler{interfaces::MakeSignalHandler(\n        wallet->ShowProgress.connect([&progress](const std::string&, int percent) { progress(percent); }))};\n    int start_height{0};\n    uint256 start_block;\n    if (!wallet->chain().findFirstBlockWithTimeAndHeight(time - TIMESTAMP_WINDOW, 0,\n                                                         interfaces::FoundBlock().hash(start_block).height(start_height))) {\n        return {Status::Done};\n    }\n    const wallet::ScanResult result{wallet->Scanner().Scan(start_block, start_height, /*max_height=*/{}, reserver, /*save_progress=*/true)};\n    if (result.status == wallet::ScanResult::SUCCESS) return {Status::Done};\n    if (result.status == wallet::ScanResult::FAILURE) return {Status::Failed};\n    ImportRescanResult stopped{Status::Stopped};\n    int64_t last_time{0};\n    if (result.last_failed_block.IsNull() && !result.last_scanned_block.IsNull() &&\n        wallet->chain().findBlock(result.last_scanned_block, interfaces::FoundBlock().time(last_time))) {\n        stopped.checkpoint = last_time;\n    }\n    return stopped;\n}\n\nQString ImportErrorText(const wallet::ImportError& error)\n{\n    const bilingual_str& message{error.wallet_error.message};\n    return QString::fromStdString(message.translated.empty() ? message.original : message.translated);\n}\n} // namespace\n\nbool RescanControl::attach(std::function<void()> abort)\n{\n    const std::lock_guard lock{m_mutex};\n    if (m_cancelled) return false;\n    m_abort = std::move(abort);\n    return true;\n}\n\nvoid RescanControl::detach()\n{\n    const std::lock_guard lock{m_mutex};\n    m_abort = nullptr;\n}\n\nvoid RescanControl::cancel()\n{\n    const std::lock_guard lock{m_mutex};\n    m_cancelled = true;\n    if (m_abort) m_abort();\n}\n\nbool RescanControl::cancelled() const\n{\n    const std::lock_guard lock{m_mutex};\n    return m_cancelled;\n}\n\nWalletQmlController::WalletQmlController(interfaces::Node& node, QObject *parent)\n    : QObject(parent)\n    , m_node(node)\n    , m_empty_wallet(new WalletQmlModel(&node, this))\n    , m_selected_wallet(m_empty_wallet)\n    , m_wallet_command_executor(std::make_shared<BackendExecutor>())\n    , m_load_notifications(std::make_shared<WalletLoadNotifications>())\n    , m_notification_bridge(new QObject, [](QObject* bridge) {\n        if (QThread::currentThread() == bridge->thread()) delete bridge;\n        else bridge->deleteLater();\n    })\n    , m_open_local_path_fn([](const QString& path) {\n        return QDesktopServices::openUrl(QUrl::fromLocalFile(path));\n    })\n    , m_resume_import_fn([&node](const std::string& wallet_name, int64_t time, RescanControl& control,\n                                 const std::function<void(int)>& progress) {\n        return ResumeImport(node, wallet_name, time, control, progress);\n    })\n{\n    m_empty_wallet->setNode(&m_node);\n    m_wallet_command_executor->setObjectName(QStringLiteral(\"wallet-commands\"));\n    connect(m_wallet_command_executor.get(), &BackendExecutor::drained, this, [this] {\n        m_controller_drained = true;\n        checkShutdownFinished();",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · c6ff067c1dff..60c9d57773fb

2026-11-25T19:04:19Z · gpt-6-luna

gui#1148The -reverselayout help gives the wrong direction for RTL languagesqml/guiargs.cppaddressed
Assessment

The -reverselayout help now says it reverses the selected language’s layout direction, directly describing the flag’s behavior rather than implying that it enables RTL layout.

path_diff: qml/guiargs.cpp

[
  {
    "evidence_id": "fe14537f79b1462781c57877e90373bd",
    "finding_id": "finding:8",
    "kind": "path_diff",
    "new_head": "d72c4d9aa262fc999ac2956c032a19ad3ea7683c",
    "old_head": "bbaf12d52e9392115986241ac3c1b7a2ae38f7f8",
    "path": "qml/guiargs.cpp",
    "source_generation": 1,
    "source_job_id": 3099,
    "text": "diff --git a/qml/guiargs.cpp b/qml/guiargs.cpp\nindex 5791a23ca4..37eab9359a 100644\n--- a/qml/guiargs.cpp\n+++ b/qml/guiargs.cpp\n@@ -11,7 +11,7 @@ void SetupQmlGuiArgs(ArgsManager& argsman)\n     argsman.AddArg(\"-choosedatadir\", \"Choose data directory on startup (default: 0)\", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);\n     argsman.AddArg(\"-lang=<lang>\", \"Set language, for example \\\"de_DE\\\" (default: system locale)\", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);\n     argsman.AddArg(\"-min\", \"Start minimized\", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);\n-    argsman.AddArg(\"-reverselayout\", \"Mirror the layout as for a right-to-left language (default: 0)\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::GUI);\n+    argsman.AddArg(\"-reverselayout\", \"Reverse the layout direction of the selected language (default: 0)\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::GUI);\n     argsman.AddArg(\"-resetguisettings\", \"Reset all settings changed in the GUI\", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);\n     argsman.AddHiddenArgs({\"-qml_onboarded\", \"-qml_receive_address_types\"});\n #ifdef ENABLE_TEST_AUTOMATION\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · bbaf12d52e93..d72c4d9aa262

2026-11-25T19:31:11Z · gpt-6-luna

gui#1148The Arabic layout test does not verify catalog loadingtest/functional/qml_test_settings_display.pyaddressed
Assessment

After selecting Arabic, the test now asserts that displayLanguageRow.title equals the Arabic catalog translation, in addition to checking layout mirroring. This verifies that the application-specific translation loaded.

path_diff: test/functional/qml_test_settings_display.py

[
  {
    "evidence_id": "0060190195974fd9ae37a9efaed5ca8b",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "d72c4d9aa262fc999ac2956c032a19ad3ea7683c",
    "old_head": "bbaf12d52e9392115986241ac3c1b7a2ae38f7f8",
    "path": "test/functional/qml_test_settings_display.py",
    "source_generation": 1,
    "source_job_id": 3099,
    "text": "diff --git a/test/functional/qml_test_settings_display.py b/test/functional/qml_test_settings_display.py\nindex 0c0792ea0d..d62675ad66 100644\n--- a/test/functional/qml_test_settings_display.py\n+++ b/test/functional/qml_test_settings_display.py\n@@ -109,7 +109,9 @@ def test_language_direction(gui):\n         assert gui.get_property(\"displayLanguageRow\", \"mirrored\") is False\n         select_language(gui, \"arabic\", \"language_ar\")\n         gui.wait_for_property(\"displayLanguageRow\", \"mirrored\", True, timeout_ms=3000)\n-        print(\"  Arabic mirrors the layout  PASSED\")\n+        language_title = gui.get_property(\"displayLanguageRow\", \"title\")\n+        assert language_title == \"اللغة\", language_title\n+        print(\"  Arabic mirrors and translates the layout  PASSED\")\n \n         select_language(gui, \"español\", \"language_es\")\n         gui.wait_for_property(\"displayLanguageRow\", \"mirrored\", False, timeout_ms=3000)\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · bbaf12d52e93..d72c4d9aa262

2026-11-25T19:31:11Z · gpt-6-luna

gui#1148Untranslated date patterns discard regional order and clock conventionsqml/pages/wallet/TransactionDetail.qmladdressed
Assessment

The affected date displays now use LocaleFormat.shortDateTimePattern, which is derived from the selected QLocale’s ShortFormat, instead of fixed month-first, 12-hour patterns. This preserves locale-specific date order and clock conventions while using the locale-aware formatting path.

path_diff: qml/pages/wallet/TransactionDetail.qml

[
  {
    "evidence_id": "2a08128cea4043148bd5bba6d885b19a",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "d72c4d9aa262fc999ac2956c032a19ad3ea7683c",
    "old_head": "bbaf12d52e9392115986241ac3c1b7a2ae38f7f8",
    "path": "qml/pages/wallet/TransactionDetail.qml",
    "source_generation": 1,
    "source_job_id": 3099,
    "text": "diff --git a/qml/pages/wallet/TransactionDetail.qml b/qml/pages/wallet/TransactionDetail.qml\nindex ba6cc3761c..37347ee38f 100644\n--- a/qml/pages/wallet/TransactionDetail.qml\n+++ b/qml/pages/wallet/TransactionDetail.qml\n@@ -125,10 +125,8 @@ Page {\n                     amount: root.amount\n                     hidesAmount: true\n                     amountColor: root.inactive ? Theme.color.neutral7 : root.incoming ? Theme.color.txIncoming : Theme.color.neutral9\n-                    //: Qt date and time format pattern for when a transaction happened\n-                    readonly property string datePattern: qsTr(\"MMM d, yyyy h:mm AP\")\n                     subtitle: root.actionLabel + (root.transactionData.timestamp\n-                        ? \" · \" + LocaleFormat.formatDate(new Date(root.transactionData.timestamp * 1000), datePattern) : \"\")\n+                        ? \" · \" + LocaleFormat.formatDate(new Date(root.transactionData.timestamp * 1000), LocaleFormat.shortDateTimePattern) : \"\")\n                     iconComponent: ActivityIcon {\n                         objectName: \"transactionDetailIcon\"\n                         iconSize: 48\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · bbaf12d52e93..d72c4d9aa262

2026-11-25T19:31:11Z · gpt-6-luna

gui#1148Retained Activity date labels keep the previous languageqml/models/activityfilterproxymodel.cppaddressed
Assessment

The new localeChanged connection emits dataChanged for existing rows with SectionLabelRole and DateTimeLabelRole, addressing stale retained Activity labels. A regression test populates the model, switches languages, checks the notification roles, and verifies the translated label.

path_diff: qml/models/activityfilterproxymodel.cpp

[
  {
    "evidence_id": "090b1bee468546f38a80bcccff7a1fd8",
    "finding_id": "finding:2",
    "kind": "path_diff",
    "new_head": "d72c4d9aa262fc999ac2956c032a19ad3ea7683c",
    "old_head": "bbaf12d52e9392115986241ac3c1b7a2ae38f7f8",
    "path": "qml/models/activityfilterproxymodel.cpp",
    "source_generation": 1,
    "source_job_id": 3099,
    "text": "diff --git a/qml/models/activityfilterproxymodel.cpp b/qml/models/activityfilterproxymodel.cpp\nindex 66d5cd81e4..b67dab0453 100644\n--- a/qml/models/activityfilterproxymodel.cpp\n+++ b/qml/models/activityfilterproxymodel.cpp\n@@ -77,6 +77,9 @@ ActivityFilterProxyModel::ActivityFilterProxyModel(QObject* parent)\n                 || roles.contains(TransactionActivityModel::NetAmountSatRole) || roles.contains(TransactionActivityModel::IsPendingRequestRole)) invalidatePendingBalance();\n         });\n     connect(this, &ActivityFilterProxyModel::displayUnitChanged, this, &ActivityFilterProxyModel::pendingBalanceChanged);\n+    connect(&LocaleFormat::instance(), &LocaleFormat::localeChanged, this, [this] {\n+        if (rowCount()) Q_EMIT dataChanged(index(0, 0), index(rowCount() - 1, 0), {SectionLabelRole, DateTimeLabelRole});\n+    });\n }\n \n QHash<int, QByteArray> ActivityFilterProxyModel::roleNames() const\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · bbaf12d52e93..d72c4d9aa262

2026-11-25T19:31:11Z · gpt-6-luna

gui#1148Coin rows and saved payment requests no longer show the yearqml/components/CoinsList.qmladdressed
Assessment

Coin rows and saved payment-request cards now format their dates with LocaleFormat.shortDateTimePattern rather than the yearless fixed pattern. This restores the locale’s short date-time format, which includes the year in the relevant regional pattern; the diff shows both affected displays changed.

path_diff: qml/components/CoinsList.qml

[
  {
    "evidence_id": "675ba7589cfb4df59e6a754152c08126",
    "finding_id": "finding:1",
    "kind": "path_diff",
    "new_head": "d72c4d9aa262fc999ac2956c032a19ad3ea7683c",
    "old_head": "bbaf12d52e9392115986241ac3c1b7a2ae38f7f8",
    "path": "qml/components/CoinsList.qml",
    "source_generation": 1,
    "source_job_id": 3099,
    "text": "diff --git a/qml/components/CoinsList.qml b/qml/components/CoinsList.qml\nindex 45c949ce2e..e7694a09e6 100644\n--- a/qml/components/CoinsList.qml\n+++ b/qml/components/CoinsList.qml\n@@ -285,8 +285,7 @@ ColumnLayout {\n                     CoreText { visible: !root.coins || root.coins.groupBy !== \"address\"; Layout.fillWidth: true; text: coinRow.address; horizontalAlignment: Text.AlignLeft; textStyle: Theme.text.monoCaption; color: Theme.color.neutral7; wrap: false; elide: Text.ElideMiddle }\n                     CoreText {\n                         Layout.fillWidth: true\n-                        //: Qt date format pattern for when a coin was received\n-                        text: LocaleFormat.formatDate(coinRow.date, qsTr(\"MMM d, h:mm AP\"))\n+                        text: LocaleFormat.formatDate(coinRow.date, LocaleFormat.shortDateTimePattern)\n                         horizontalAlignment: Text.AlignLeft\n                         textStyle: Theme.text.caption\n                         color: Theme.color.neutral7\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · bbaf12d52e93..d72c4d9aa262

2026-11-25T19:31:11Z · gpt-6-luna

gui#1057Early commits refine a modal that the series deletesqml/components/WatchOnlyExportModal.qmlunclear
Assessment

There is no captured evidence about the commit sequence or its reorganization in the new head, so whether the early commits still refine the deleted modal cannot be determined.

Source report · 598abdbeb3a5..780a6a245a3c

2026-11-25T10:41:24Z · gpt-6-luna

gui#1057Tr() hides destination errors from lupdateqml/walletfiledestination.cppaddressed
Assessment

The Tr() wrapper was removed and each reported destination error now passes its literal directly to QCoreApplication::translate(), including the missing-folder message with its translator comment retained.

path_diff: qml/walletfiledestination.cpp; new_source: qml/walletfiledestination.cpp

[
  {
    "evidence_id": "4188a8b6a74d42b5ac693ee6bd2e599e",
    "finding_id": "finding:8",
    "kind": "path_diff",
    "new_head": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "old_head": "598abdbeb3a5abc2db4083646cf609590e5f955c",
    "path": "qml/walletfiledestination.cpp",
    "source_generation": 6,
    "source_job_id": 3097,
    "text": "diff --git a/qml/walletfiledestination.cpp b/qml/walletfiledestination.cpp\nindex 434ba4bf90..d7f72ac332 100644\n--- a/qml/walletfiledestination.cpp\n+++ b/qml/walletfiledestination.cpp\n@@ -13,11 +13,6 @@\n \n namespace {\n \n-QString Tr(const char* text)\n-{\n-    return QCoreApplication::translate(\"WalletFileDestination\", text);\n-}\n-\n QString CleanPath(const QString& path)\n {\n     const QFileInfo info{path};\n@@ -110,7 +105,7 @@ QVariantMap DescribeWalletFileDestination(const QString& path,\n                                           const QDateTime& now)\n {\n     const QString trimmed{path.trimmed()};\n-    if (trimmed.isEmpty()) return Blocked(Tr(\"Choose where to save the file.\"));\n+    if (trimmed.isEmpty()) return Blocked(QCoreApplication::translate(\"WalletFileDestination\", \"Choose where to save the file.\"));\n \n     const QUrl url{trimmed};\n     QString local{QFileInfo{url.isLocalFile() ? url.toLocalFile() : trimmed}.absoluteFilePath()};\n@@ -126,14 +121,14 @@ QVariantMap DescribeWalletFileDestination(const QString& path,\n     const QString folder{QDir::toNativeSeparators(info.absolutePath())};\n     if (!QFileInfo{info.absolutePath()}.isDir()) {\n         //: %1 is a folder path.\n-        return Blocked(Tr(\"The folder %1 does not exist.\").arg(folder));\n+        return Blocked(QCoreApplication::translate(\"WalletFileDestination\", \"The folder %1 does not exist.\").arg(folder));\n     }\n-    if (info.isDir()) return Blocked(Tr(\"A folder with this name already exists.\"));\n+    if (info.isDir()) return Blocked(QCoreApplication::translate(\"WalletFileDestination\", \"A folder with this name already exists.\"));\n \n     const QString resolved{CleanPath(info.absolutePath()) + '/' + info.fileName()};\n     for (const QString& protected_path : protected_paths) {\n         if (!protected_path.isEmpty() && IsSameOrInside(resolved, CleanPath(protected_path))) {\n-            return Blocked(Tr(\"Wallet files can't be saved in the wallets folder. Choose another location.\"));\n+            return Blocked(QCoreApplication::translate(\"WalletFileDestination\", \"Wallet files can't be saved in the wallets folder. Choose another location.\"));\n         }\n     }\n \n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 150,
    "evidence_id": "a634ddeceedf444ab572913c66b4c073",
    "finding_id": "finding:8",
    "kind": "new_source",
    "line": 1,
    "new_head": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "old_head": "598abdbeb3a5abc2db4083646cf609590e5f955c",
    "path": "qml/walletfiledestination.cpp",
    "revision": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "source_generation": 6,
    "source_job_id": 3097,
    "text": "// Copyright (c) 2026 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <qml/walletfiledestination.h>\n\n#include <QCoreApplication>\n#include <QDir>\n#include <QFile>\n#include <QFileInfo>\n#include <QRegularExpression>\n#include <QUrl>\n\nnamespace {\n\nQString CleanPath(const QString& path)\n{\n    const QFileInfo info{path};\n    const QString canonical{info.canonicalFilePath()};\n    return canonical.isEmpty() ? QDir::cleanPath(info.absoluteFilePath()) : canonical;\n}\n\nbool IsSameOrInside(const QString& path, const QString& root)\n{\n#if defined(Q_OS_WIN) || defined(Q_OS_MACOS)\n    constexpr Qt::CaseSensitivity sensitivity{Qt::CaseInsensitive};\n#else\n    constexpr Qt::CaseSensitivity sensitivity{Qt::CaseSensitive};\n#endif\n    if (root.isEmpty()) return false;\n    if (path.compare(root, sensitivity) == 0) return true;\n    const QString prefix{root.endsWith('/') ? root : root + '/'};\n    return path.startsWith(prefix, sensitivity);\n}\n\nQVariantMap Blocked(const QString& error)\n{\n    return {{QStringLiteral(\"status\"), QStringLiteral(\"blocked\")}, {QStringLiteral(\"error\"), error}};\n}\n\n} // namespace\n\nbool IsWalletDatabaseFile(const QString& path)\n{\n    QFile file{path};\n    if (!file.open(QIODevice::ReadOnly)) return false;\n    const QByteArray header{file.read(72)};\n\n    if (header.startsWith(QByteArray(\"SQLite format 3\\0\", 16))) {\n        // Core stores the network magic as the application id.\n        return header.size() >= 72 && header.mid(68, 4) != QByteArray(4, '\\0');\n    }\n\n    // Berkeley DB btree magic, in either byte order, as Core's IsBDBFile.\n    if (file.size() < 4096 || header.size() < 16) return false;\n    const QByteArray magic{header.mid(12, 4)};\n    return magic == QByteArray(\"\\x00\\x05\\x31\\x62\", 4) || magic == QByteArray(\"\\x62\\x31\\x05\\x00\", 4);\n}\n\nQString DefaultWalletFileName(const QString& wallet_name, bool watch_only, const QDate& date)\n{\n    static const QRegularExpression separators{QStringLiteral(\"[\\\\\\\\/]\")};\n    static const QRegularExpression reserved{QStringLiteral(\"[:*?\\\"<>|]\")};\n    const QStringList parts{wallet_name.split(separators, Qt::SkipEmptyParts)};\n    QString name{parts.isEmpty() ? QString{} : parts.last().trimmed()};\n    name.replace(reserved, QStringLiteral(\"_\"));\n    if (name.isEmpty()) name = QStringLiteral(\"wallet\");\n\n    const QString stamp{date.toString(QStringLiteral(\"yyyy-MM-dd\"))};\n    return watch_only\n        ? QStringLiteral(\"%1-watchonly-%2.dat\").arg(name, stamp)\n        : QStringLiteral(\"%1-%2.bak\").arg(name, stamp);\n}\n\nQString KeepBothPath(const QString& path, bool watch_only, const QDateTime& now)\n{\n    // A stamp left by an earlier save is replaced, not appended to.\n    static const QRegularExpression old_stamp{QStringLiteral(\"-\\\\d{4}-\\\\d{2}-\\\\d{2}(-\\\\d{4})?(-\\\\d+)?$\")};\n    static const QRegularExpression watch_only_label{QStringLiteral(\"-watchonly$\"), QRegularExpression::CaseInsensitiveOption};\n    const QFileInfo info{path};\n    QString base{info.completeBaseName()};\n    base.remove(old_stamp);\n    // The existing file can be the other type, so its label and suffix are not kept.\n    base.remove(watch_only_label);\n    if (base.isEmpty()) base = QStringLiteral(\"wallet\");\n    if (watch_only) base += QStringLiteral(\"-watchonly\");\n    const QString stem{base + '-' + now.toString(QStringLiteral(\"yyyy-MM-dd-HHmm\"))};\n    const bool known_suffix{info.suffix().compare(QStringLiteral(\"bak\"), Qt::CaseInsensitive) == 0 ||\n                            info.suffix().compare(QStringLiteral(\"dat\"), Qt::CaseInsensitive) == 0};\n    const QString suffix{known_suffix ? (watch_only ? QStringLiteral(\".dat\") : QStringLiteral(\".bak\"))\n                         : info.suffix().isEmpty() ? QString{} : '.' + info.suffix()};\n    const QDir dir{info.absoluteDir()};\n\n    for (int count{1};; ++count) {\n        const QString name{count == 1 ? stem + suffix : QStringLiteral(\"%1-%2%3\").arg(stem).arg(count).arg(suffix)};\n        const QString candidate{dir.filePath(name)};\n        if (!QFileInfo::exists(candidate)) return candidate;\n    }\n}\n\nQVariantMap DescribeWalletFileDestination(const QString& path,\n                                          bool watch_only,\n                                          const QString& wallet_name,\n                                          const QStringList& protected_paths,\n                                          const QDateTime& now)\n{\n    const QString trimmed{path.trimmed()};\n    if (trimmed.isEmpty()) return Blocked(QCoreApplication::translate(\"WalletFileDestination\", \"Choose where to save the file.\"));\n\n    const QUrl url{trimmed};\n    QString local{QFileInfo{url.isLocalFile() ? url.toLocalFile() : trimmed}.absoluteFilePath()};\n    if (QFileInfo{local}.isDir()) {\n        local = QDir{local}.filePath(DefaultWalletFileName(wallet_name, watch_only, now.date()));\n    } else {\n        static const QRegularExpression known_suffix{QStringLiteral(\"\\\\.(bak|dat)$\"),\n                                                     QRegularExpression::CaseInsensitiveOption};\n        if (!known_suffix.match(local).hasMatch()) local += watch_only ? QStringLiteral(\".dat\") : QStringLiteral(\".bak\");\n    }\n\n    const QFileInfo info{local};\n    const QString folder{QDir::toNativeSeparators(info.absolutePath())};\n    if (!QFileInfo{info.absolutePath()}.isDir()) {\n        //: %1 is a folder path.\n        return Blocked(QCoreApplication::translate(\"WalletFileDestination\", \"The folder %1 does not exist.\").arg(folder));\n    }\n    if (info.isDir()) return Blocked(QCoreApplication::translate(\"WalletFileDestination\", \"A folder with this name already exists.\"));\n\n    const QString resolved{CleanPath(info.absolutePath()) + '/' + info.fileName()};\n    for (const QString& protected_path : protected_paths) {\n        if (!protected_path.isEmpty() && IsSameOrInside(resolved, CleanPath(protected_path))) {\n            return Blocked(QCoreApplication::translate(\"WalletFileDestination\", \"Wallet files can't be saved in the wallets folder. Choose another location.\"));\n        }\n    }\n\n    QVariantMap result{\n        {QStringLiteral(\"path\"), QDir::toNativeSeparators(local)},\n        {QStringLiteral(\"folder\"), folder},\n        {QStringLiteral(\"fileName\"), info.fileName()},\n        {QStringLiteral(\"error\"), QString{}},\n    };\n    if (!info.exists()) {\n        result.insert(QStringLiteral(\"status\"), QStringLiteral(\"available\"));\n        return result;\n    }\n    const QFileInfo keep_both{KeepBothPath(local, watch_only, now)};\n    result.insert(QStringLiteral(\"status\"), IsWalletDatabaseFile(local) ? QStringLiteral(\"walletFile\") : QStringLiteral(\"otherFile\"));\n    result.insert(QStringLiteral(\"keepBothPath\"), QDir::toNativeSeparators(keep_both.absoluteFilePath()));\n    result.insert(QStringLiteral(\"keepBothFileName\"), keep_both.fileName());\n    return result;\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 598abdbeb3a5..780a6a245a3c

2026-11-25T10:41:24Z · gpt-6-luna

gui#1057Descriptor footer overstates receive/change coverageqml/pages/wallet/WalletDescriptors.qmladdressed
Assessment

The list footer now claims receive-and-change coverage only when every listed descriptor's coversChange flag is true; otherwise it omits that claim, retaining only the fingerprint where applicable.

path_diff: qml/pages/wallet/WalletDescriptors.qml; new_source: qml/pages/wallet/WalletDescriptors.qml

[
  {
    "evidence_id": "1ed6ca7e06564433afdbfad313a1a189",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "old_head": "598abdbeb3a5abc2db4083646cf609590e5f955c",
    "path": "qml/pages/wallet/WalletDescriptors.qml",
    "source_generation": 6,
    "source_job_id": 3097,
    "text": "diff --git a/qml/pages/wallet/WalletDescriptors.qml b/qml/pages/wallet/WalletDescriptors.qml\nindex 48838e3059..40491b8b0c 100644\n--- a/qml/pages/wallet/WalletDescriptors.qml\n+++ b/qml/pages/wallet/WalletDescriptors.qml\n@@ -19,9 +19,8 @@ SettingsPage {\n     property var exports: []\n     // Descriptors that no longer give out addresses but may still hold funds.\n     property var inactiveExports: []\n-    // Descriptors that importdescriptors can't take without private keys.\n-    property int omittedCount: 0\n     readonly property var completeExports: exports.concat(inactiveExports)\n+    readonly property bool coversChange: completeExports.length > 0 && completeExports.every(item => item.coversChange)\n     readonly property string sharedFingerprint: {\n         const fingerprints = new Set(completeExports.map(item => item.fingerprint))\n         return fingerprints.size === 1 ? completeExports[0].fingerprint : \"\"\n@@ -37,7 +36,6 @@ SettingsPage {\n     function refresh() {\n         exports = wallet ? wallet.descriptorExports() : []\n         inactiveExports = wallet ? wallet.inactiveDescriptorExports() : []\n-        omittedCount = wallet ? wallet.descriptorImportOmittedCount() : 0\n     }\n \n     function shortKey(key) {\n@@ -50,13 +48,6 @@ SettingsPage {\n         return scripts.join(\"(\") + \"(\" + shortKey(item.xpub) + \")\".repeat(scripts.length)\n     }\n \n-    function copyAll() {\n-        const json = wallet ? wallet.descriptorImportJson() : \"\"\n-        if (json === \"\") return\n-        clipboard.setText(json)\n-        copyAllTimer.restart()\n-    }\n-\n     Component.onCompleted: refresh()\n     onWalletChanged: refresh()\n \n@@ -65,28 +56,26 @@ SettingsPage {\n         function onDescriptorExportsChanged() { root.refresh() }\n     }\n \n-    Timer {\n-        id: copyAllTimer\n-        interval: 1000\n-    }\n-\n-    CoreText {\n+    DescriptorPrivacyNote {\n         objectName: \"descriptorsListNote\"\n         Layout.fillWidth: true\n-        text: qsTr(\"Anyone with these descriptors can see all of this wallet's addresses and transactions, but cannot spend from it.\")\n-        textStyle: Theme.text.description\n-        color: Theme.color.neutral7\n-        horizontalAlignment: Text.AlignLeft\n     }\n \n     FormSection {\n         objectName: \"descriptorsTypeList\"\n         Layout.fillWidth: true\n         title: qsTr(\"Address types\")\n-        footerText: root.sharedFingerprint !== \"\"\n-            //: %1 is the wallet's BIP32 master key fingerprint.\n-            ? qsTr(\"Fingerprint %1. Each descriptor covers receive and change addresses.\").arg(root.sharedFingerprint)\n-            : qsTr(\"Each descriptor covers receive and change addresses.\")\n+        // Imported descriptors can cover receive addresses only.\n+        footerText: {\n+            if (root.sharedFingerprint === \"\") {\n+                return root.coversChange ? qsTr(\"Each descriptor covers receive and change addresses.\") : \"\"\n+            }\n+            return root.coversChange\n+                //: %1 is the wallet's BIP32 master key fingerprint.\n+                ? qsTr(\"Fingerprint %1. Each descriptor covers receive and change addresses.\").arg(root.sharedFingerprint)\n+                //: %1 is the wallet's BIP32 master key fingerprint.\n+                : qsTr(\"Fingerprint %1.\").arg(root.sharedFingerprint)\n+        }\n \n         Repeater {\n             model: root.completeExports\n@@ -116,30 +105,10 @@ SettingsPage {\n         }\n     }\n \n-    NeutralButton {\n-        objectName: \"descriptorsCopyAll\"\n-        buttonSize: NeutralButton.Large\n-        visible: root.completeExports.length > 0\n-        enabled: !(root.wallet && root.wallet.watchOnlyWalletExportPending)\n-        Layout.fillWidth: true\n-        //: Copies every descriptor as JSON for Bitcoin Core's importdescriptors command.\n-        text: copyAllTimer.running ? qsTr(\"Copied\") : qsTr(\"Copy all for Bitcoin Core\")\n-        onClicked: root.copyAll()\n-    }\n-\n-    CoreText {\n-        objectName: \"descriptorsCopyAllNote\"\n+    DescriptorCopyAll {\n         visible: root.completeExports.length > 0\n         Layout.fillWidth: true\n-        //: \"importdescriptors\" is a Bitcoin Core command and is not translated.\n-        text: qsTr(\"Copies every descriptor, with when it was created, as JSON for importdescriptors. Import it into a Bitcoin Core wallet without private keys.\")\n-            + (root.omittedCount === 0 ? \"\"\n-               : \" \" + (root.omittedCount === 1\n-                   ? qsTr(\"1 older descriptor needs private keys to find its addresses, so it is left out. To keep it, save a watch-only copy from Back up or export wallet.\")\n-                   //: %1 is a number of descriptors.\n-                   : qsTr(\"%1 older descriptors need private keys to find their addresses, so they are left out. To keep them, save a watch-only copy from Back up or export wallet.\").arg(root.omittedCount)))\n-        textStyle: Theme.text.caption\n-        color: Theme.color.neutral7\n-        horizontalAlignment: Text.AlignLeft\n+        wallet: root.wallet\n+        clipboard: root.clipboard\n     }\n }\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 114,
    "evidence_id": "45187f8f302b4608b9008c3aa37011fe",
    "finding_id": "finding:7",
    "kind": "new_source",
    "line": 59,
    "new_head": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "old_head": "598abdbeb3a5abc2db4083646cf609590e5f955c",
    "path": "qml/pages/wallet/WalletDescriptors.qml",
    "revision": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "source_generation": 6,
    "source_job_id": 3097,
    "text": "    DescriptorPrivacyNote {\n        objectName: \"descriptorsListNote\"\n        Layout.fillWidth: true\n    }\n\n    FormSection {\n        objectName: \"descriptorsTypeList\"\n        Layout.fillWidth: true\n        title: qsTr(\"Address types\")\n        // Imported descriptors can cover receive addresses only.\n        footerText: {\n            if (root.sharedFingerprint === \"\") {\n                return root.coversChange ? qsTr(\"Each descriptor covers receive and change addresses.\") : \"\"\n            }\n            return root.coversChange\n                //: %1 is the wallet's BIP32 master key fingerprint.\n                ? qsTr(\"Fingerprint %1. Each descriptor covers receive and change addresses.\").arg(root.sharedFingerprint)\n                //: %1 is the wallet's BIP32 master key fingerprint.\n                : qsTr(\"Fingerprint %1.\").arg(root.sharedFingerprint)\n        }\n\n        Repeater {\n            model: root.completeExports\n\n            ListRow {\n                required property var modelData\n                required property int index\n                readonly property bool inactive: index >= root.exports.length\n                readonly property string rowId: inactive ? \"inactive\" + (index - root.exports.length) : modelData.id\n                objectName: \"descriptorsType_\" + rowId\n                Layout.fillWidth: true\n                title: modelData.label\n                description: inactive\n                    //: Shown under an address type in the descriptors list for keys that no longer give out new addresses, such as keys from before a password was set. %1 is a shortened descriptor.\n                    ? qsTr(\"Previous key %1\").arg(root.shortDescriptor(modelData))\n                    : root.shortDescriptor(modelData)\n                showDivider: index < root.completeExports.length - 1\n                showsDisclosureIndicator: !inactive\n                onClicked: if (!inactive) root.descriptorRequested(modelData.id)\n                trailingItem: CopyButton {\n                    objectName: \"descriptorsTypeCopy_\" + rowId\n                    displayMode: CopyButton.IconOnly\n                    Accessible.name: qsTr(\"Copy %1 descriptor\").arg(modelData.label)\n                    onCopyRequested: root.clipboard.setText(modelData.descriptor)\n                }\n            }\n        }\n    }\n\n    DescriptorCopyAll {\n        visible: root.completeExports.length > 0\n        Layout.fillWidth: true\n        wallet: root.wallet\n        clipboard: root.clipboard\n    }\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 598abdbeb3a5..780a6a245a3c

2026-11-25T10:41:24Z · gpt-6-luna

gui#1057The PR description still promises descriptor and key file savingqml/pages/wallet/WalletDescriptorDetail.qmlunclear
Assessment

The supplied new-head evidence shows clipboard copying and the watch-only database export, but does not show whether the PR description or screenshots were updated or whether saving the selected payload to a text file remains intended.

path_diff: qml/pages/wallet/WalletDescriptorDetail.qml; new_source: qml/pages/wallet/WalletDescriptorDetail.qml

[
  {
    "evidence_id": "2438df1b4b2842a29ed464be80b9561d",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "old_head": "598abdbeb3a5abc2db4083646cf609590e5f955c",
    "path": "qml/pages/wallet/WalletDescriptorDetail.qml",
    "source_generation": 6,
    "source_job_id": 3097,
    "text": "diff --git a/qml/pages/wallet/WalletDescriptorDetail.qml b/qml/pages/wallet/WalletDescriptorDetail.qml\nindex 37be305349..4f3cbf4e9c 100644\n--- a/qml/pages/wallet/WalletDescriptorDetail.qml\n+++ b/qml/pages/wallet/WalletDescriptorDetail.qml\n@@ -21,6 +21,8 @@ SettingsPage {\n     property bool extendedKeyFormat: false\n     // Previous keys of this type are separate descriptors.\n     property bool hasPreviousKeys: false\n+    // Opened without the Descriptors list, so it also offers what the list does.\n+    property bool standalone: false\n     readonly property bool extendedKeyAvailable: !!exportItem && exportItem.extendedKey !== \"\"\n     readonly property string payload: !exportItem ? \"\"\n         : extendedKeyFormat ? exportItem.extendedKey : exportItem.descriptor\n@@ -61,6 +63,12 @@ SettingsPage {\n         interval: 1000\n     }\n \n+    DescriptorPrivacyNote {\n+        objectName: \"descriptorsPrivacyNote\"\n+        visible: root.standalone\n+        Layout.fillWidth: true\n+    }\n+\n     SegmentedPicker {\n         objectName: \"descriptorsFormatPicker\"\n         Layout.fillWidth: true\n@@ -71,13 +79,18 @@ SettingsPage {\n     }\n \n     // A bare key has no script type, so an importer can guess another one.\n+    // SegWit keys carry theirs in the ypub or zpub prefix.\n     ToastBanner {\n-        objectName: \"descriptorsTaprootWarning\"\n+        readonly property string addressType: root.exportItem ? root.exportItem.id : \"\"\n+        objectName: \"descriptorsScriptTypeWarning\"\n         Layout.fillWidth: true\n-        shown: root.extendedKeyFormat && !!root.exportItem && root.exportItem.id === \"bech32m\"\n+        shown: root.extendedKeyFormat && (addressType === \"bech32m\" || addressType === \"legacy\")\n         tone: ToastBanner.Warning\n-        textObjectName: \"descriptorsTaprootWarningText\"\n-        text: qsTr(\"This key doesn't record that it is for Taproot. A wallet that imports it as another address type will give out addresses this wallet doesn't watch, and payments to them won't show here. Use the descriptor unless the other wallet asks for a Taproot key.\")\n+        textObjectName: \"descriptorsScriptTypeWarningText\"\n+        text: addressType === \"legacy\"\n+            //: \"Bitcoin Core App\" is this app's name.\n+            ? qsTr(\"This key doesn't record that it is for Legacy addresses. A wallet that imports it as another address type will give out addresses this wallet doesn't watch, and payments to them won't show here. Bitcoin Core App, like many wallets, imports a bare key as SegWit. Use the descriptor unless the other wallet asks for a Legacy key.\")\n+            : qsTr(\"This key doesn't record that it is for Taproot. A wallet that imports it as another address type will give out addresses this wallet doesn't watch, and payments to them won't show here. Use the descriptor unless the other wallet asks for a Taproot key.\")\n     }\n \n     Rectangle {\n@@ -181,4 +194,11 @@ SettingsPage {\n             : qsTr(\"Copy descriptor\")\n         onClicked: root.copy()\n     }\n+\n+    DescriptorCopyAll {\n+        visible: root.standalone && !!root.exportItem\n+        Layout.fillWidth: true\n+        wallet: root.wallet\n+        clipboard: root.clipboard\n+    }\n }\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 204,
    "evidence_id": "08b63e2c0d4e4b43b8ef5064abafd7ae",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 152,
    "new_head": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "old_head": "598abdbeb3a5abc2db4083646cf609590e5f955c",
    "path": "qml/pages/wallet/WalletDescriptorDetail.qml",
    "revision": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "source_generation": 6,
    "source_job_id": 3097,
    "text": "            valueTextStyle: Theme.text.monoDescription\n            showDivider: !root.extendedKeyFormat\n        }\n\n        ValueRow {\n            objectName: \"descriptorsChains\"\n            visible: !root.extendedKeyFormat && !!root.exportItem\n            Layout.fillWidth: true\n            //: Derivation branches the descriptor covers: receiving addresses and change addresses.\n            title: qsTr(\"Chains\")\n            value: !root.exportItem ? \"\"\n                : root.exportItem.changeChain === \"\" ? qsTr(\"Receive %1\").arg(root.exportItem.receiveChain)\n                : qsTr(\"Receive %1, change %2\").arg(root.exportItem.receiveChain).arg(root.exportItem.changeChain)\n            showDivider: false\n        }\n    }\n\n    CoreText {\n        objectName: \"descriptorsNote\"\n        Layout.fillWidth: true\n        text: {\n            if (!root.exportItem) return \"\"\n            //: \"Back up or export wallet\" is the wallet settings action that saves a watch-only copy of the whole wallet.\n            let note = qsTr(\"Only includes funds on %1 addresses. For a copy of the whole wallet, use Back up or export wallet.\").arg(root.exportItem.label)\n            if (root.hasPreviousKeys) {\n                //: %1 is an address type. \"Copy all for Bitcoin Core\" is a button on the Descriptors page.\n                note += \" \" + qsTr(\"Funds on previous %1 keys are not included. To include them, use Copy all for Bitcoin Core on Descriptors, or save a watch-only copy.\").arg(root.exportItem.label)\n            }\n            return note\n        }\n        textStyle: Theme.text.caption\n        color: Theme.color.neutral7\n        horizontalAlignment: Text.AlignLeft\n    }\n\n    NeutralButton {\n        objectName: \"descriptorsCopyButton\"\n        buttonSize: NeutralButton.Large\n        Layout.fillWidth: true\n        enabled: root.payload !== \"\"\n        text: copiedTimer.running ? qsTr(\"Copied\")\n            : root.extendedKeyFormat ? qsTr(\"Copy extended key\")\n            : qsTr(\"Copy descriptor\")\n        onClicked: root.copy()\n    }\n\n    DescriptorCopyAll {\n        visible: root.standalone && !!root.exportItem\n        Layout.fillWidth: true\n        wallet: root.wallet\n        clipboard: root.clipboard\n    }\n}",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 598abdbeb3a5..780a6a245a3c

2026-11-25T10:41:24Z · gpt-6-luna

gui#1057Single-type shortcut hides Core JSON export and the privacy noteqml/pages/wallet/WalletSettingsStack.qmlunclear
Assessment

The follow-up assessment was invalid: follow-up evidence belongs to another finding or comparison.

invalid_assessment

Source report · 598abdbeb3a5..780a6a245a3c

2026-11-25T10:41:24Z · gpt-6-luna

gui#1057Legacy extended-key export lacks a script-type warningqml/pages/wallet/WalletDescriptorDetail.qmladdressed
Assessment

The extended-key warning now appears for Legacy as well as Taproot; its Legacy-specific text explains that this app imports a bare key as SegWit and recommends using the descriptor unless a Legacy key is specifically requested.

path_diff: qml/pages/wallet/WalletDescriptorDetail.qml; new_source: qml/pages/wallet/WalletDescriptorDetail.qml

[
  {
    "evidence_id": "9dff3930f3be4d1b83b9ba08094f2976",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "old_head": "598abdbeb3a5abc2db4083646cf609590e5f955c",
    "path": "qml/pages/wallet/WalletDescriptorDetail.qml",
    "source_generation": 6,
    "source_job_id": 3097,
    "text": "diff --git a/qml/pages/wallet/WalletDescriptorDetail.qml b/qml/pages/wallet/WalletDescriptorDetail.qml\nindex 37be305349..4f3cbf4e9c 100644\n--- a/qml/pages/wallet/WalletDescriptorDetail.qml\n+++ b/qml/pages/wallet/WalletDescriptorDetail.qml\n@@ -21,6 +21,8 @@ SettingsPage {\n     property bool extendedKeyFormat: false\n     // Previous keys of this type are separate descriptors.\n     property bool hasPreviousKeys: false\n+    // Opened without the Descriptors list, so it also offers what the list does.\n+    property bool standalone: false\n     readonly property bool extendedKeyAvailable: !!exportItem && exportItem.extendedKey !== \"\"\n     readonly property string payload: !exportItem ? \"\"\n         : extendedKeyFormat ? exportItem.extendedKey : exportItem.descriptor\n@@ -61,6 +63,12 @@ SettingsPage {\n         interval: 1000\n     }\n \n+    DescriptorPrivacyNote {\n+        objectName: \"descriptorsPrivacyNote\"\n+        visible: root.standalone\n+        Layout.fillWidth: true\n+    }\n+\n     SegmentedPicker {\n         objectName: \"descriptorsFormatPicker\"\n         Layout.fillWidth: true\n@@ -71,13 +79,18 @@ SettingsPage {\n     }\n \n     // A bare key has no script type, so an importer can guess another one.\n+    // SegWit keys carry theirs in the ypub or zpub prefix.\n     ToastBanner {\n-        objectName: \"descriptorsTaprootWarning\"\n+        readonly property string addressType: root.exportItem ? root.exportItem.id : \"\"\n+        objectName: \"descriptorsScriptTypeWarning\"\n         Layout.fillWidth: true\n-        shown: root.extendedKeyFormat && !!root.exportItem && root.exportItem.id === \"bech32m\"\n+        shown: root.extendedKeyFormat && (addressType === \"bech32m\" || addressType === \"legacy\")\n         tone: ToastBanner.Warning\n-        textObjectName: \"descriptorsTaprootWarningText\"\n-        text: qsTr(\"This key doesn't record that it is for Taproot. A wallet that imports it as another address type will give out addresses this wallet doesn't watch, and payments to them won't show here. Use the descriptor unless the other wallet asks for a Taproot key.\")\n+        textObjectName: \"descriptorsScriptTypeWarningText\"\n+        text: addressType === \"legacy\"\n+            //: \"Bitcoin Core App\" is this app's name.\n+            ? qsTr(\"This key doesn't record that it is for Legacy addresses. A wallet that imports it as another address type will give out addresses this wallet doesn't watch, and payments to them won't show here. Bitcoin Core App, like many wallets, imports a bare key as SegWit. Use the descriptor unless the other wallet asks for a Legacy key.\")\n+            : qsTr(\"This key doesn't record that it is for Taproot. A wallet that imports it as another address type will give out addresses this wallet doesn't watch, and payments to them won't show here. Use the descriptor unless the other wallet asks for a Taproot key.\")\n     }\n \n     Rectangle {\n@@ -181,4 +194,11 @@ SettingsPage {\n             : qsTr(\"Copy descriptor\")\n         onClicked: root.copy()\n     }\n+\n+    DescriptorCopyAll {\n+        visible: root.standalone && !!root.exportItem\n+        Layout.fillWidth: true\n+        wallet: root.wallet\n+        clipboard: root.clipboard\n+    }\n }\n",
    "truncated": false,
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  },
  {
    "bounded": true,
    "end_line": 196,
    "evidence_id": "1c9892fca98a4e00864e8b844c8a179d",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 47,
    "new_head": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "old_head": "598abdbeb3a5abc2db4083646cf609590e5f955c",
    "path": "qml/pages/wallet/WalletDescriptorDetail.qml",
    "revision": "780a6a245a3ce263bf4bbd9de14e44818784ba6d",
    "source_generation": 6,
    "source_job_id": 3097,
    "text": "        if (payload === \"\") return\n        clipboard.setText(payload)\n        copiedTimer.restart()\n    }\n\n    Component.onCompleted: refresh()\n    onWalletChanged: refresh()\n    onAddressTypeChanged: refresh()\n\n    Connections {\n        target: root.wallet && root.wallet.descriptorExportsChanged ? root.wallet : null\n        function onDescriptorExportsChanged() { root.refresh() }\n    }\n\n    Timer {\n        id: copiedTimer\n        interval: 1000\n    }\n\n    DescriptorPrivacyNote {\n        objectName: \"descriptorsPrivacyNote\"\n        visible: root.standalone\n        Layout.fillWidth: true\n    }\n\n    SegmentedPicker {\n        objectName: \"descriptorsFormatPicker\"\n        Layout.fillWidth: true\n        //: Export formats: an output descriptor, or a bare xpub/ypub/zpub key for wallets that only accept those.\n        model: [qsTr(\"Descriptor\"), {text: qsTr(\"Extended key\"), enabled: root.extendedKeyAvailable}]\n        currentIndex: root.extendedKeyFormat ? 1 : 0\n        onSelected: index => root.setExtendedKeyFormat(index === 1)\n    }\n\n    // A bare key has no script type, so an importer can guess another one.\n    // SegWit keys carry theirs in the ypub or zpub prefix.\n    ToastBanner {\n        readonly property string addressType: root.exportItem ? root.exportItem.id : \"\"\n        objectName: \"descriptorsScriptTypeWarning\"\n        Layout.fillWidth: true\n        shown: root.extendedKeyFormat && (addressType === \"bech32m\" || addressType === \"legacy\")\n        tone: ToastBanner.Warning\n        textObjectName: \"descriptorsScriptTypeWarningText\"\n        text: addressType === \"legacy\"\n            //: \"Bitcoin Core App\" is this app's name.\n            ? qsTr(\"This key doesn't record that it is for Legacy addresses. A wallet that imports it as another address type will give out addresses this wallet doesn't watch, and payments to them won't show here. Bitcoin Core App, like many wallets, imports a bare key as SegWit. Use the descriptor unless the other wallet asks for a Legacy key.\")\n            : qsTr(\"This key doesn't record that it is for Taproot. A wallet that imports it as another address type will give out addresses this wallet doesn't watch, and payments to them won't show here. Use the descriptor unless the other wallet asks for a Taproot key.\")\n    }\n\n    Rectangle {\n        readonly property real side: Math.min(parent.width, 240)\n        Layout.preferredWidth: side\n        Layout.preferredHeight: side\n        Layout.alignment: Qt.AlignHCenter\n        radius: Theme.radius.cardInset\n        color: Theme.color.qrBackground\n\n        QRImage {\n            objectName: \"descriptorsQRImage\"\n            anchors.fill: parent\n            anchors.margins: Theme.space.l\n            code: root.payload\n            backgroundColor: Theme.color.qrBackground\n            foregroundColor: Theme.color.qrForeground\n        }\n    }\n\n    AddressLabel {\n        objectName: \"descriptorsKeyText\"\n        visible: root.extendedKeyFormat\n        Layout.fillWidth: true\n        address: visible && root.exportItem ? root.exportItem.extendedKey : \"\"\n        textStyle: Theme.text.monoDescription\n        clipboard: root.clipboard\n        surfaceLevel: 0\n    }\n\n    DescriptorText {\n        objectName: \"descriptorsDetail\"\n        visible: !root.extendedKeyFormat && !!root.exportItem\n        Layout.fillWidth: true\n        parts: visible ? root.exportItem.descriptorParts : ({})\n        descriptor: visible ? root.exportItem.descriptor : \"\"\n        clipboard: root.clipboard\n    }\n\n    FormSection {\n        Layout.fillWidth: true\n\n        ValueRow {\n            objectName: \"descriptorsFingerprint\"\n            visible: !!root.exportItem && root.exportItem.fingerprint !== \"\"\n            Layout.fillWidth: true\n            //: BIP32 fingerprint of the wallet's master key.\n            title: qsTr(\"Master fingerprint\")\n            value: root.exportItem ? root.exportItem.fingerprint : \"\"\n            valueTextStyle: Theme.text.monoDescription\n        }\n\n        ValueRow {\n            objectName: \"descriptorsDerivationPath\"\n            visible: !!root.exportItem && root.exportItem.derivationPath !== \"\"\n            Layout.fillWidth: true\n            title: qsTr(\"Derivation path\")\n            value: root.exportItem ? root.exportItem.derivationPath : \"\"\n            valueTextStyle: Theme.text.monoDescription\n            showDivider: !root.extendedKeyFormat\n        }\n\n        ValueRow {\n            objectName: \"descriptorsChains\"\n            visible: !root.extendedKeyFormat && !!root.exportItem\n            Layout.fillWidth: true\n            //: Derivation branches the descriptor covers: receiving addresses and change addresses.\n            title: qsTr(\"Chains\")\n            value: !root.exportItem ? \"\"\n                : root.exportItem.changeChain === \"\" ? qsTr(\"Receive %1\").arg(root.exportItem.receiveChain)\n                : qsTr(\"Receive %1, change %2\").arg(root.exportItem.receiveChain).arg(root.exportItem.changeChain)\n            showDivider: false\n        }\n    }\n\n    CoreText {\n        objectName: \"descriptorsNote\"\n        Layout.fillWidth: true\n        text: {\n            if (!root.exportItem) return \"\"\n            //: \"Back up or export wallet\" is the wallet settings action that saves a watch-only copy of the whole wallet.\n            let note = qsTr(\"Only includes funds on %1 addresses. For a copy of the whole wallet, use Back up or export wallet.\").arg(root.exportItem.label)\n            if (root.hasPreviousKeys) {\n                //: %1 is an address type. \"Copy all for Bitcoin Core\" is a button on the Descriptors page.\n                note += \" \" + qsTr(\"Funds on previous %1 keys are not included. To include them, use Copy all for Bitcoin Core on Descriptors, or save a watch-only copy.\").arg(root.exportItem.label)\n            }\n            return note\n        }\n        textStyle: Theme.text.caption\n        color: Theme.color.neutral7\n        horizontalAlignment: Text.AlignLeft\n    }\n\n    NeutralButton {\n        objectName: \"descriptorsCopyButton\"\n        buttonSize: NeutralButton.Large\n        Layout.fillWidth: true\n        enabled: root.payload !== \"\"\n        text: copiedTimer.running ? qsTr(\"Copied\")\n            : root.extendedKeyFormat ? qsTr(\"Copy extended key\")\n            : qsTr(\"Copy descriptor\")\n        onClicked: root.copy()\n    }",
    "repository_id": "gui",
    "repository": "bitcoin-core/gui-qml",
    "repository_url": "https://github.com/bitcoin-core/gui-qml"
  }
]

Source report · 598abdbeb3a5..780a6a245a3c

2026-11-25T10:41:24Z · gpt-6-luna

Conceptual concerns

The archaeology pass can complete without publishing a concern. Published conceptual concerns are tracked separately from code findings.

160 saved reviews completed archaeology research; 0 saved and 0 published a conceptual concern.

StatusReviews
candidate3
drop9
failed2
no_concern145
unresolved3

Median citations: N/A; median alternatives: N/A.