wallet, rpc: add verify_balance option to importdescriptors #36236

Closed
musaHaruna wants to merge 4 commits from wallet/importdescriptors-utxo-check into master AGit
musaHaruna commented 2026-09-13 07:23:54 +00:00 (Migrated from github.com)

Another Attempt to fix #28898

When importing descriptors, users may provide a timestamp that is too recent. This causes the rescan to miss older payments, leaving the wallet with an incomplete balance.

This PR adds an optional verify_balance argument to importdescriptors, which is false by default.

When enabled, it scans the chainstate UTXO set once for outputs belonging to the wallet’s known scripts. If it finds outputs missing from the wallet, it uses the earliest missing output’s block height to extend the rescan backwards where needed, then scans forward. An earlier requested timestamp is still respected so older transaction history is scanned as well.

After rescanning, it compares the wallet’s confirmed mature UTXO outpoints with those collected from the initial chainstate scan. The response includes an info object showing the verification result, UTXO counts and scan details.

For example:

bitcoin-cli -rpcwallet=restore importdescriptors \
  '[{"desc":"<descriptor>","timestamp":"now"}]' true
Example response when verification recovers payments:
[
  {
    "success": true,
    "info": {
      "status": "matched after recovery",
      "utxo_check": true,
      "scanned_blocks": 22,
      "wallet_utxos": 2,
      "chain_utxos": 2,
      "scan_start_height": 101,
      "snapshot_block": "0000000000000001234..01f",
      "snapshot_height": 122,
      "recovery_start_height": 101
    }
  }
]

If the sets still differ, verification reports "utxo_check": false with an error explaining the mismatch. For example, the info object may contain:

Failure Response
{
  "status": "unmatched",
  "utxo_check": false,
  "scanned_blocks": 22,
  "wallet_utxos": 2,
  "chain_utxos": 1,
  "scan_start_height": 101,
  "snapshot_block": "00000000000000001234...01f",
  "snapshot_height": 122,
  "recovery_start_height": 101
}

Verification failures leave the descriptors imported and keep any transactions already discovered. Required blocks being unavailable is reported explicitly. No automatic retry or fallback rescan is performed.

A match verifies the compared UTXO sets; it does not guarantee complete transaction history. Older spent transactions still require an appropriate timestamp or a full rescan. Changes to relevant UTXOs during verification can also cause a mismatch because the final wallet check is compared with the initial chainstate scan.

Functional tests cover recovery with recent timestamps, preserving older requested history, mismatches, mempool transactions, invalid requests and unavailable blocks.

Another Attempt to fix [#28898](https://github.com/bitcoin/bitcoin/issues/28898) When importing descriptors, users may provide a timestamp that is too recent. This causes the rescan to miss older payments, leaving the wallet with an incomplete balance. This PR adds an optional `verify_balance` argument to importdescriptors, which is false by default. When enabled, it scans the chainstate UTXO set once for outputs belonging to the wallet’s known scripts. If it finds outputs missing from the wallet, it uses the earliest missing output’s block height to extend the rescan backwards where needed, then scans forward. An earlier requested timestamp is still respected so older transaction history is scanned as well. After rescanning, it compares the wallet’s confirmed mature UTXO outpoints with those collected from the initial chainstate scan. The response includes an info object showing the verification result, UTXO counts and scan details. For example: ```bash bitcoin-cli -rpcwallet=restore importdescriptors \ '[{"desc":"<descriptor>","timestamp":"now"}]' true ``` <details> <summary><strong>Example response when verification recovers payments:</strong></summary> ```json [ { "success": true, "info": { "status": "matched after recovery", "utxo_check": true, "scanned_blocks": 22, "wallet_utxos": 2, "chain_utxos": 2, "scan_start_height": 101, "snapshot_block": "0000000000000001234..01f", "snapshot_height": 122, "recovery_start_height": 101 } } ] ``` </details> If the sets still differ, verification reports `"utxo_check": false` with an error explaining the mismatch. For example, the info object may contain: <details> <summary><strong>Failure Response</strong></summary> ```json { "status": "unmatched", "utxo_check": false, "scanned_blocks": 22, "wallet_utxos": 2, "chain_utxos": 1, "scan_start_height": 101, "snapshot_block": "00000000000000001234...01f", "snapshot_height": 122, "recovery_start_height": 101 } ``` </details> Verification failures leave the descriptors imported and keep any transactions already discovered. Required blocks being unavailable is reported explicitly. No automatic retry or fallback rescan is performed. A match verifies the compared UTXO sets; it does not guarantee complete transaction history. Older spent transactions still require an appropriate timestamp or a full rescan. Changes to relevant UTXOs during verification can also cause a mismatch because the final wallet check is compared with the initial chainstate scan. Functional tests cover recovery with recent timestamps, preserving older requested history, mismatches, mempool transactions, invalid requests and unavailable blocks.
DrahtBot commented 2026-09-13 07:24:02 +00:00 (Migrated from github.com)

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

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept NACK polespinasa

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #35989 (wallet: fix crash on importdescriptors with a range ending at 2^31-1 by shuv-amp)
  • #35377 (wallet: Allow importing of descriptors without private keys when the wallet has the private keys by achow101)

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

LLM Linter (✨ experimental)

Possible typos and grammar issues:

  • This error could potentially caused by data corruption. -> This error could potentially be caused by data corruption. [missing “be”; current wording is grammatically broken]

Possible places where comparison-specific test macros should replace generic comparisons:

  • [test/functional/wallet_importdescriptors.py] assert result["info"]["scan_start_height"] <= first_header["height"] -> replace with assert_greater_than_or_equal(first_header["height"], result["info"]["scan_start_height"])
  • [test/functional/wallet_importdescriptors.py] assert node.pruneblockchain(funding_height) >= funding_height -> replace with assert_greater_than_or_equal(node.pruneblockchain(funding_height), funding_height)

2026-09-17 20:08:47

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36236 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36236.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36236#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept NACK | [polespinasa](https://github.com/bitcoin/bitcoin/pull/36236#issuecomment-6575319251) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#35989](https://github.com/bitcoin/bitcoin/pull/35989) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35989.svg"></sub> (wallet: fix crash on importdescriptors with a range ending at 2^31-1 by shuv-amp) * [#35377](https://github.com/bitcoin/bitcoin/pull/35377) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35377.svg"></sub> (wallet: Allow importing of descriptors without private keys when the wallet has the private keys by achow101) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3--> ### LLM Linter (✨ experimental) Possible typos and grammar issues: - `This error could potentially caused by data corruption.` -> `This error could potentially be caused by data corruption.` [missing “be”; current wording is grammatically broken] Possible places where comparison-specific test macros should replace generic comparisons: - [test/functional/wallet_importdescriptors.py] `assert result["info"]["scan_start_height"] <= first_header["height"]` -> replace with `assert_greater_than_or_equal(first_header["height"], result["info"]["scan_start_height"])` - [test/functional/wallet_importdescriptors.py] `assert node.pruneblockchain(funding_height) >= funding_height` -> replace with `assert_greater_than_or_equal(node.pruneblockchain(funding_height), funding_height)` <sup>2026-09-17 20:08:47</sup>
DrahtBot commented 2026-09-13 08:26:53 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/34745132536/job/103691544345
LLM reason (✨ experimental): CI failed because the IWYU (include-what-you-use) check reported missing/incorrect includes and exited with “Failure generated from IWYU.”

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/34745132536/job/103691544345</sub> <sub>LLM reason (✨ experimental): CI failed because the IWYU (include-what-you-use) check reported missing/incorrect includes and exited with “Failure generated from IWYU.”</sub> <details><summary>Hints</summary> Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example: * Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch. * A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test. * An intermittent issue. Leave a comment here, if you need help tracking down a confusing failure. </details>
DrahtBot commented 2026-09-14 13:10:37 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
DrahtBot commented 2026-09-17 02:27:56 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
musaHaruna (Migrated from github.com) reviewed 2026-09-17 20:15:48 +00:00
musaHaruna (Migrated from github.com) left a comment

Rebased on the latest master and resolved the conflict with #34861.

Since #34861 moved descriptor importing and rescanning into the shared importer, I moved the UTXO verification scan into src/wallet/imports.cpp as well. The RPC now passes verify_balance to ProcessDescriptorsImport(...), and backup.cpp only handles parsing the RPC argument and formatting the result. compare

Rebased on the latest master and resolved the conflict with [#34861](https://github.com/bitcoin/bitcoin/pull/34861). Since [#34861](https://github.com/bitcoin/bitcoin/pull/34861) moved descriptor importing and rescanning into the shared importer, I moved the UTXO verification scan into `src/wallet/imports.cpp` as well. The RPC now passes `verify_balance` to `ProcessDescriptorsImport(...),` and `backup.cpp` only handles parsing the RPC argument and formatting the result. [compare](https://github.com/bitcoin/bitcoin/compare/3eccd3463c565995bee869a041ea40d197d27fba..4da013f50bb8a3808cfddc2ca567a345fc58d296)
First-time contributor

Base: 09e22fbbb0caafbd2167657c2a8d409ae435b2cc
Head: 4da013f50bb8a3808cfddc2ca567a345fc58d296

Design and approach

The chainstate scan cannot be interrupted by abortrescan (src/node/coin.cpp:45, head)

When verify_balance=true, this loop traverses the chainstate cursor without checking the wallet scanner’s abort flag. abortrescan sets that flag, but the import checks it only after ScanWalletUTXOSet returns, so an accepted abort cannot stop this potentially chainstate-wide phase. Pass a cancellation check to the scan and poll it during traversal so abort can end the work promptly.

🟡 Minor

Iterator errors can be reported as a complete UTXO scan (src/node/coin.cpp:54, head)

If the underlying LevelDB iterator encounters a read error while advancing, it can become invalid and report the error through status(). The cursor interface does not expose that status, so this loop treats the invalid cursor as normal exhaustion and returns success with a potentially incomplete set; verification could then report a false match. Expose and check terminal iterator status before declaring the scan complete. No ordinary caller producing an iterator I/O error was identified, so production impact is conditional on such a storage failure.

Review coverage was incomplete. The archaeology review had incomplete evidence. The adversarial review had incomplete evidence. The adversarial_glm review did not complete.

Full review report

<!-- forgejo-review-bot:bitcoin/bitcoin --> Base: `09e22fbbb0caafbd2167657c2a8d409ae435b2cc` Head: `4da013f50bb8a3808cfddc2ca567a345fc58d296` ##### Design and approach **The chainstate scan cannot be interrupted by `abortrescan`** (src/node/coin.cpp:45, head) When `verify_balance=true`, this loop traverses the chainstate cursor without checking the wallet scanner’s abort flag. `abortrescan` sets that flag, but the import checks it only after `ScanWalletUTXOSet` returns, so an accepted abort cannot stop this potentially chainstate-wide phase. Pass a cancellation check to the scan and poll it during traversal so abort can end the work promptly. ##### 🟡 Minor **Iterator errors can be reported as a complete UTXO scan** (src/node/coin.cpp:54, head) If the underlying LevelDB iterator encounters a read error while advancing, it can become invalid and report the error through `status()`. The cursor interface does not expose that status, so this loop treats the invalid cursor as normal exhaustion and returns success with a potentially incomplete set; verification could then report a false match. Expose and check terminal iterator status before declaring the scan complete. No ordinary caller producing an iterator I/O error was identified, so production impact is conditional on such a storage failure. Review coverage was incomplete. The archaeology review had incomplete evidence. The adversarial review had incomplete evidence. The adversarial_glm review did not complete. [Full review report](<https://review.fish.foo/traces/36236-4da013f50bb8a3808cfddc2ca567a345fc58d296-421-1.html>)
DrahtBot commented 2026-10-09 01:25:15 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
polespinasa commented 2026-11-02 10:52:33 +00:00 (Migrated from github.com)

Following what I said in https://github.com/bitcoin/bitcoin/issues/28898#issuecomment-6575096663

I tend to concept NACK.
If the user knows or thinks that the birth time might be wrong he should just set an older birth time, or just set it to 0.
If he already imported and knows that the balance is wrong they can just rescan.
If what we want is to help users that don't know that they might be missing some funds I would prefer to add this UTXOset check by default, without adding a new parameter to importdescriptors and inform the user with a warning (importdescriptorsalready returns warnings). If I am not wrong we could even inform the user at which hight those funds are.

Following what I said in https://github.com/bitcoin/bitcoin/issues/28898#issuecomment-6575096663 I tend to concept NACK. If the user knows or thinks that the birth time might be wrong he should just set an older birth time, or just set it to `0`. If he already imported and knows that the balance is wrong they can just rescan. If what we want is to help users that don't know that they might be missing some funds I would prefer to add this UTXOset check by default, without adding a new parameter to `importdescriptors` and inform the user with a warning (`importdescriptors`already returns warnings). If I am not wrong we could even inform the user at which hight those funds are.
musaHaruna commented 2026-11-02 11:03:46 +00:00 (Migrated from github.com)

Thanks @polespinasa for the feedback.

If what we want is to help users that don't know that they might be missing some funds I would prefer to add this UTXOset check by default, without adding a new parameter to importdescriptors and inform the user with a warning (importdescriptorsalready returns warnings). If I am not wrong we could even inform the user at which hight those funds are.

I think this could be nice to have. I’ll close this PR and plan to open another with the above suggested approach. Before opening a replacement PR, I’ll benchmark UTXO set scans to assess whether the performance cost is acceptable for a default check.

Thanks @polespinasa for the feedback. > If what we want is to help users that don't know that they might be missing some funds I would prefer to add this UTXOset check by default, without adding a new parameter to `importdescriptors` and inform the user with a warning (`importdescriptors`already returns warnings). If I am not wrong we could even inform the user at which hight those funds are. I think this could be nice to have. I’ll close this PR and plan to open another with the above suggested approach. Before opening a replacement PR, I’ll benchmark UTXO set scans to assess whether the performance cost is acceptable for a default check.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36236
No description provided.