mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
wallet: fix crash on importdescriptors with a range ending at 2^31-1 #35989
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35989
Loading…
Reference in a new issue
No description provided.
Delete branch "wallet-descriptor-range-overflow"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
WalletDescriptorstores an exclusive range end inint32_t. Importing[2147483647, 2147483647]produces an end of2^31, which narrows to a negativevalue and aborts the node during keypool top-up. An import without a range can
hit the same issue with an oversized
-keypool.Check the exclusive end before constructing the wallet descriptor, covering
both explicit and default ranges. The bound stays wallet-specific: scanning
RPCs still accept
INT32_MAXas an inclusive endpoint.Also calculate the keypool top-up endpoint in
int64_tbefore checking itsbound, and reject reversed ranges before computing
high - lowinCheckDescriptorRangeBounds. These fix the overflows reached bykeypoolrefill INT32_MAXafter advancing a descriptor, and by[INT64_MAX, 0],respectively. Regression tests cover all three fixes.
I tested on macOS arm64 with Clang 22 and UBSan passed: 34 targeted unit
cases and the importdescriptors, keypool, deriveaddresses (RPC and CLI),
scantxoutset, and scanblocks functional tests.
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.
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:
wallet_importdescriptorsto separaterun_test()contents into specific functions by nebula-21)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.
Concept ACK
I reproduced the crash both ways on master.
Only the overflow case changes behaviour here, and I couldn't find a test for it. A
keypoolrefill 2147483647reaches this addition without going through an import, as long as every active descriptor has already advanced one index. On master, UBSan flags it. Worth a case so it doesn't come back?🐙 This pull request conflicts with the target branch and needs rebase.
Added. It only fails under UBSan though: the wrapped sum is negative, so
std::max()discarded it anyway and
range_endcomes out the same either way.ACK
def4fb0101I reviewed the code. The changes are straightforward and focused on fixing the reported issues.
Testing
The following results are from local test runs.
Compared master
b811aeabad94ef48cd0f0fb1d2fcc456594aeedbwith the PR tip:[2147483647,2147483647]terminated master. The PR returned error-8and remained responsive.-keypool=3000000000terminated master. The PR returned error-8and remained responsive.keypoolrefill 2147483647after advancing every active descriptor to index 1 terminated master. The PR returned error-4and remained responsive.Non-blocking follow-ups
Possbile follow-ups, worth considering separately from this PR:
-keypoolvalues. For example: accepted as a wallet configuration option without an upper-bound check (wallet.cpp)TopUpWithDBshould return failure when the requested endpoint is unrepresentable, instead of leaving the range unchanged and returningtrue(plus writes the unchanged descriptor). This is separate from the testedkeypoolrefillRPC, which correctly returns an error.nit , readability choice:
I'd keep
GetEnd()here, it's explicit about the lower bound.Follow-up, agreed. On the reported import the descriptor write happens inside
AddWalletDescriptorwith the assert after it, and activation is back inProcessDescriptorImportonce that call returns, so the record persists unactivated even withactive=true. On reloadLoad()runs zero iterations over the inverted range andTopUpKeyPoolskips it for being inactive. The wallet reopens, but none of that descriptor'sscripts are registered.
I thought
UpdateWalletDescriptormight put the assert back in play since it resetsm_max_cached_index, but it also assigns the incoming descriptor overm_wallet_descriptor, sothe old range is gone before the top up. Haven't tested recovery on an affected wallet.
There's narrowing before the addition too:
TopUpWithDBassignsm_keypool_sizeto anunsigned int, so-keypool=4294968296gives atarget_sizeof 1000. The member keeps the fullvalue, so the no-range import path still rejects it with -8 here. A bound of
INT32_MAXwould berepresentable and still ask for two billion derivations, so the limit has to be about work, not
just the type.
I'd keep it as is here and look at the return value with its callers separately.
keypoolrefilldiscards the bool, the -4 you saw is
GetKeyPoolSize() < kpSize, which sums across active spkmsrather than reporting the descriptor that failed.
UpdateWithSigningProviderthrowsstd::runtime_error("Could not top up scriptPubKeys")on false andMarkUnusedAddresseslogs"Topping up keypool failed (locked wallet)", so changing it means touching those too. The
unchanged write is pre-existing,
keypoolrefill 1on a full keypool does the same, though thatonly says it isn't new, not that
trueis the right answer.I agree with these points and think they can be handled in follow-up PRs. They don't block this fix, so this PR can be merged as is.
tACK
def4fb0101Built and ran both tests. Also tried it by hand: importing
[2147483647, 2147483647]into a watch-only wallet is rejected with "End of range is too high", the node stays up and the wallet is still empty after a restart. Without the first two commits the new importdescriptors case takes the node down as expected.One note on the wallet_keypool.py case: it also passes on master in a non-sanitizer build. The wrapped sum ends up below GetEnd(), so std::max just keeps the old end and keypoolrefill fails with the same -4. So it only catches the overflow under UBSan. Still worth having, maybe with a comment in the test saying that.
Not something this PR needs to solve, but
[2147482648, 2147482648]is accepted both with and without this PR (range_end 2147482649 still fits in int32_t), and the top up then derives every index from 0, so the RPC doesn't come back for a very long time. That's the existing O(range_start) cost in TopUpWithDB, #36245 addresses it. The only thing that changes here is that the next_index + target_size addition no longer overflows, so a UBSan build stops aborting on it.Concept ACK
Before

After
🐙 This pull request conflicts with the target branch and needs rebase.
There is another (unraelated) overflow that this PR could fix, see https://github.com/bitcoin/bitcoin/pull/34861#discussion_r4021705766
Rebased onto
d48e76e689, adapting the import guard towallet/imports.cpp.Added a separate commit for the range-validation overflow reported by @Rob1Ham
and linked by @polespinasa, including the suggested regression test. The new
test fails before the fix and passes after it under UBSan. The targeted unit
and functional tests passed.
tACK
457c9e8999Tested locally. The code hasn't changed since my previous review, and I still consider it good.
In
1889440f82"wallet: reject unrepresentable descriptor import ranges"This should be in
CheckDescriptorRangeBoundsso that all bounds checks are in the same place. This makes other RPCs likederiveaddressesalso be covered by the check.ACK
457c9e8999This is a behaviour change as now descriptors with a previously accepted range will now fail. Probably worth a release note.
Base:
aef8a04966d7ab6c04edc5d19b733e78205405deHead:
93c8aec3fbc8c5a2fcc834c4acc1b7d96bffa9a0No verified findings are available from this partial review.
Review coverage was incomplete. The archaeology review had incomplete evidence. The alternatives experiment had incomplete evidence. The adversarial review had incomplete evidence. The adversarial_glm review did not complete.
Full review report
in
867ad9bffbwallet: fix integer overflow in descriptor keypool top upThis can now be a db writte no-op as maybe
new_range_enddid not change.Maybe:
I'd keep the write unconditional. It persists the whole record, not just range_end, and two callers rely on it when the end doesn't move.
With the diff, wallet_migration.py fails in test_basic with 8 descriptors instead of 11: CreateFromMigration uses a keypool size of 0, so the end never moves and this is the only write of the migrated descriptors. MarkUnusedAddresses also relies on it to persist next_index, so when the range already covers next_index + keypool, it's lost on restart and getnewaddress can hand out an already paid address again.
Master writes unconditionally too, and in the overflow case it also keeps GetEnd(), so this PR doesn't add a new no-op write. Skipping the write would need those two callers to persist their own changes, and together with the return value check that I'd do separately.
Added a release note in
2b87954093as suggested by @polespinasa.ACK
2b87954093Tested locally.
I would not mention
deriveaddressesandscantxoutsetnot mentioning them already means that this change does not affect them.Removed in
93c8aec3fb.ACK
93c8aec3fbACK
93c8aec3fb