Skip to content

wallet, rpc: add verify_balance option to importdescriptors - #36236

Closed
musaHaruna wants to merge 4 commits into
bitcoin:masterfrom
musaHaruna:wallet/importdescriptors-utxo-check
Closed

musaHaruna wants to merge 4 commits into
bitcoin:masterfrom
musaHaruna:wallet/importdescriptors-utxo-check

Conversation

@musaHaruna

Copy link
Copy Markdown
Contributor

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.

@DrahtBot

DrahtBot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

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

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 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.

Add an interface function to scan the chainstate for coins matching
the requested output scripts, fill the output map with matching
coins, and set the best block of the scanned snapshot.
Collect unique scripts from the wallet's script managers and scan
chainstate for matching unspent outputs. Filter out coinbase outputs
that are immature at the scanned block height.

Return the matching coins, searched scripts, and the scan's block hash
and height so callers can identify missing outputs and report which
chainstate was scanned.
Add an optional verify_balance argument to check the wallet's confirmed
mature UTXOs against a chainstate scan for known wallet scripts.

If the wallet is missing outputs, extend the rescan to the earliest
missing output when it is before the requested scan start. Keep the
requested timestamp range so older transaction history is still scanned.

Return the comparison result, UTXO counts and scan details. Verification
failures leave descriptors and any discovered transactions in the wallet.
The option defaults to false.
Cover missing UTXO recovery, timestamp handling, mismatch reporting and mempool transactions.

Check that pruned blocks fail verification without removing the
imported descriptor.
@musaHaruna
musaHaruna force-pushed the wallet/importdescriptors-utxo-check branch from 3eccd34 to 4da013f Compare September 17, 2026 20:08

@musaHaruna musaHaruna left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

@DrahtBot

DrahtBot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

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

@polespinasa

Copy link
Copy Markdown
Member

Following what I said in #28898 (comment)

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.

@musaHaruna

Copy link
Copy Markdown
Contributor Author

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.

@musaHaruna musaHaruna closed this Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

wallet RPC to double-check the calculated balance

3 participants