Skip to content

wallet may silently skip to sync history #36828

Open

Description

@maflcko

This is from a ci failure, but I think it can happen in reality as well. It would be trivial to fix the test, but maybe this should be fixed in the wallet?

The basic idea is that some block connection events on the scheduler thread may be processed while the wallet is failing to load due to a pre-prune locator. Thus, on the next load, the corrupt locator is used and the rescan is silently skipped.

From https://github.com/bitcoin/bitcoin/actions/runs/42834240037/job/129901508274?pr=36827#step:11:23736 shows that the balance is wrong:

                                     File "D:\a\bitcoin\bitcoin/test/functional/wallet_assumeutxo.py", line 271, in run_test
                                       assert_equal(w.getbalance(), 34)
                                       ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
                                     File "D:\a\bitcoin\bitcoin\test\functional\test_framework\util.py", line 95, in assert_equal
                                       raise AssertionError("not(%s)" % " == ".join(str(arg) for arg in (thing1, thing2) + args))
                                   AssertionError: not(15.00000000 == 34)
LLM summary of the bug (experimental)

Timeline:

  1. dumb_sync_blocks() submits blocks through height 359.
  2. Their BlockConnected callbacks are queued on the scheduler.
  3. At 15:06:17.180791, the test performs the deliberately failing loadwallet("w").
  4. Loading w registers it for validation callbacks before it discovers that the required pre-snapshot blocks are unavailable.
  5. The scheduler then delivers already-queued notifications for blocks 357–359 to this newly registered wallet:

15:06:17.184199 BlockConnected height=357
15:06:17.184613 [w] AddToWallet ... height=357
15:06:17.184868 BlockConnected height=359
15:06:17.184911 [w] Releasing wallet w..

  1. The callback at height 357 finds a wallet transaction, so CWallet::blockConnected() persists the wallet’s best-block locator at 357.
  2. The load still fails as expected because blocks needed before the snapshot are unavailable. But the failed load has now mutated w on disk.
  3. After snapshot validation completes, the final loadwallet("w") trusts that poisoned locator and rescans only 357–399:

[w] Rescanning last 42 blocks (from block 357)
[w] mapWallet.size() = 15

That produces exactly the observed 15 payments: heights 357, 360, …, 399.

So the problem is not getbalance, and not snapshot validation completing too early. It is a race between wallet-load failure and queued validation callbacks. The callback registration in AttachChain() happens before the
availability preflight; its failing path disconnects and drains notifications, but draining allows the already-queued callbacks to update and persist the wallet.

A robust fix belongs in wallet loading: perform the “are all rescan blocks available?” preflight before registering the wallet for validation notifications, or otherwise ensure callbacks delivered during a failed attach
cannot write wallet state. A test-only synchronization barrier before the expected-failing loadwallet would avoid the flake, but would mask the underlying persistence bug.

Activity

  1. achow101 commented on Nov 10, 2026

    @achow101
    Member

    Can you reliably reproduce the race?

  2. Yudis-bit commented on Nov 14, 2026

    @Yudis-bit

    Since the availability preflight runs before any blocks are rescanned, early notification registration can be dropped.

    The race reproduces when blocks submitted prior to loadwallet are still being processed on the validation queue. In AttachChain(), handleNotifications() registers the wallet at line 3080 before checking block availability on disk. While AttachChain() holds cs_wallet during the haveBlockOnDisk backward scan, the scheduler picks up the in-flight block (height 357 in wallet_assumeutxo.py) and blocks on cs_wallet. Once AttachChain() fails and releases cs_wallet, the scheduler acquires the lock and CWallet::blockConnected() writes the height 357 locator to disk before DisconnectChainNotifications() finishes draining.

    On subsequent load, the wallet trusts that locator and skips blocks 300–356. Deferring handleNotifications() until after the availability check passes prevents the failing load from registering:

    --- a/src/wallet/wallet.cpp
    +++ b/src/wallet/wallet.cpp
    @@ -3080,2 +3080,0 @@ bool CWallet::AttachChain(...)
    -    walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
    -
    @@ -3147,0 +3148,2 @@ bool CWallet::AttachChain(...)
    +        walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
    +
    @@ -3168,0 +3171,2 @@ bool CWallet::AttachChain(...)
    +    } else {
    +        walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
  3. achow101 commented on Nov 14, 2026

    @achow101
    Member

    Deferring handleNotifications() until after the availability check passes prevents the failing load from registering:

    This introduces a different race. A block that arrives after the tip height is retrieved but before notifications are registered results in that block being missed. Early registration is to prevent this race.

  4. Yudis-bit commented on Nov 15, 2026

    @Yudis-bit

    Could we keep early registration to prevent the tip race, and gate the notification callbacks on an m_is_attached flag set under cs_wallet on attach success? A failing load then drops drained notifications without touching disk.

  5. maflcko commented on Nov 17, 2026

    @maflcko
    MemberAuthor

    Can you reliably reproduce the race?

    Sure, to repro the test issue:

    diff --git a/src/validationinterface.cpp b/src/validationinterface.cpp
    index 128f14a..06dd069 100644
    --- a/src/validationinterface.cpp
    +++ b/src/validationinterface.cpp
    @@ -17,2 +17,3 @@
     #include <util/task_runner.h>
    +#include <util/time.h>
     
    @@ -227,2 +228,7 @@ void ValidationSignals::BlockConnected(const ChainstateRole& role, std::shared_p
         auto event = [role, pblock = std::move(pblock), pindex, this] {
    +        // TEST-ONLY RACE REPRODUCTION for wallet_assumeutxo.py. Keep the
    +        // height-357 callback queued while loadwallet("w") registers its
    +        // validation handler. AttachChain() has a matching delay after the
    +        // handler is registered.
    +        if (pindex->nHeight == 357) UninterruptibleSleep(1s);
             m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockConnected(role, pblock, pindex); });
    diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
    index f509915..b2ca102 100644
    --- a/src/wallet/wallet.cpp
    +++ b/src/wallet/wallet.cpp
    @@ -3069,2 +3069,6 @@ bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interf
         walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
    +    // TEST-ONLY RACE REPRODUCTION for wallet_assumeutxo.py. cs_wallet remains
    +    // held here, so the queued height-357 callback retains this handler then
    +    // blocks trying to enter CWallet::blockConnected().
    +    UninterruptibleSleep(1s);
     

    Not sure how often it would happen in reality during IBD catch-up. Maybe just the test can be fixed for now and then this issue can be closed or revisited later?

  6. Yudis-bit commented on Nov 17, 2026

    @Yudis-bit

    A failed wallet load must not persist locator state to disk.

    Fixing only the test leaves on-disk corruption reachable in production: whenever AttachChain aborts on pruned data or in-progress assumeutxo sync, drained callbacks from concurrent blocks can write a locator at tip. The write does not even require a relevant payment, since blockConnected triggers WriteBestBlock() periodically every 144 blocks regardless. On subsequent load, the wallet skips the missing historical range, silently omitting confirmed transactions.

    Gating blockConnected and blockDisconnected on m_is_attached (set under cs_wallet upon successful return of AttachChain) ensures failed loads drop in-flight notifications without mutating disk.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions