Skip to content

Avoid full synchronous P2MR keypool top-up from MarkUnusedAddresses #14

Closed

Description

@kiwidream

Summary

DescriptorScriptPubKeyMan::MarkUnusedAddresses still performs full keypool maintenance after it advances next_index past used keypool entries. Once the P2MR getnewaddress path moves to low-watermark refill, this path should be reviewed separately so scan/recovery behavior keeps its lookahead guarantees without reintroducing large synchronous P2MR top-up work.

Handle this separately from the first getnewaddress latency patch unless that patch already has strong rescan/lookahead coverage.

Context

Current code path:

  • src/wallet/scriptpubkeyman.cpp:1490 implements DescriptorScriptPubKeyMan::MarkUnusedAddresses.
  • If the provided script belongs to the SPKM and its index is at or ahead of next_index, the method marks all cached keypool entries through that index as used.
  • If m_deferred_create_keypool_top_up is true, it only writes the descriptor state and leaves deferred refill pending.
  • Otherwise it calls TopUp() immediately. For P2MR descriptors, that can mean deriving and persisting enough PQC key material to restore the full keypool.

The planned getnewaddress optimization changes the receive-address fast path so ranged P2MR wallets do not maintain a full keypool synchronously on every address. MarkUnusedAddresses is a related but more sensitive path because it participates in detecting already-used keypool entries during wallet scanning and recovery.

Problem

After the getnewaddress low-watermark change, MarkUnusedAddresses may remain a hidden source of synchronous P2MR DB/keygen latency:

  • It can call full TopUp() after advancing one or more keypool entries.
  • P2MR top-up includes PQC private-key derivation and persistence.
  • The method can be reached from wallet transaction/script processing rather than only from explicit address-generation RPCs.

However, changing it casually can break safety:

  • The method helps maintain wallet lookahead after discovering a used keypool item.
  • Reducing refill too aggressively could hurt recovery/rescan discovery of future wallet-owned outputs.
  • Locked encrypted wallets must still use already-persisted cached entries and must not fail early because a low-watermark refill cannot run.

Proposed Direction

Once the getnewaddress low-watermark helpers exist, extend or reuse them here with a stricter correctness-first policy:

  1. Keep current behavior for non-P2MR descriptors.
  2. Keep current behavior for non-ranged descriptors.
  3. Keep deferred-create-time behavior unchanged while m_deferred_create_keypool_top_up is true.
  4. For ranged P2MR descriptors, avoid unconditional full TopUp() after marking used entries.
  5. If remaining external P2MR keypool is above the low-watermark, only persist the advanced descriptor state.
  6. If remaining keypool is at or below low-watermark:
    • Prefer scheduling the same bounded background refill used by getnewaddress when scheduler context is available.
    • If this method has no scheduler context, perform at most a bounded refill step, not a full refill, unless tests prove full refill is required for recovery safety.
  7. Preserve the explicit keypoolrefill RPC as the way to force a full refill.

The design should avoid returning or treating any address as safe unless its descriptor cache and private P2MR key material were already persisted.

Open Design Question

MarkUnusedAddresses lives in DescriptorScriptPubKeyMan, but scheduling is wallet-level. There are two likely implementation shapes:

  • Minimal SPKM-only change: replace full TopUp() with a bounded TopUp(step_target) for ranged P2MR. This is easier but still synchronous.
  • Wallet-aware change: have the caller or wallet layer schedule a bounded refill after MarkUnusedAddresses advances a ranged P2MR descriptor. This better matches the getnewaddress optimization but may require plumbing scheduler context through a path that currently does not have it.

Prefer the wallet-aware design if it can be kept small and testable. Prefer the minimal bounded synchronous step only if scheduler plumbing would turn this work into a broad refactor.

Safety Requirements

  • Do not change non-P2MR keypool semantics.
  • Do not reduce scan/recovery lookahead without explicit tests.
  • Do not make locked encrypted wallets fail while cached entries remain.
  • Do not derive or expose P2MR destinations without persisted private key material.
  • Do not run this refill while create-time deferred top-up is still pending.
  • Do not schedule duplicate refill workers for the same wallet.
  • Keep top-up persistence on the existing transaction/rollback path.
  • Keep explicit keypoolrefill behavior unchanged.

Test Plan

Add focused unit coverage in src/wallet/test/wallet_tests.cpp:

  1. MarkUnusedAddressesP2MRDoesNotFullTopUpAboveLowWatermark

    • Create a P2MR wallet with a completed keypool.
    • Mark a used cached external script while remaining keypool stays above the low-watermark.
    • Assert next_index advances and descriptor state persists.
    • Assert range_end does not jump to a full top-up target.
  2. MarkUnusedAddressesP2MRRefillsOrSchedulesAtLowWatermark

    • Drain or mark entries so remaining keypool reaches the low-watermark.
    • Assert the refill is bounded or scheduled, according to the chosen design.
    • Assert it does not perform a full synchronous refill unless that is the explicitly chosen behavior with justification.
  3. MarkUnusedAddressesP2MRPreservesRecoveryLookahead

    • Simulate discovering a used keypool item near the tail of the cached range.
    • Confirm enough lookahead is restored to discover a later wallet-owned output after the refill mechanism runs.
  4. MarkUnusedAddressesP2MRLockedWalletDoesNotFailEarly

    • Use an encrypted locked wallet with cached P2MR entries.
    • Mark used entries below the low-watermark.
    • Confirm descriptor state advances for cached entries.
    • Confirm refill failure due to lock is logged or deferred without corrupting state.
  5. Regression coverage for non-P2MR descriptors:

    • Confirm existing TopUp() behavior remains unchanged for standard ranged descriptors.

Functional tests to consider:

  • test/functional/wallet_keypool_topup.py
  • test/functional/feature_wallet_seed_recovery.py
  • Any wallet rescan/recovery test that exercises sparse address discovery.

Acceptance Criteria

  • Ranged P2MR MarkUnusedAddresses no longer performs full synchronous keypool maintenance when remaining keypool is safely above the low-watermark.
  • Low-watermark behavior matches the getnewaddress refill policy as closely as the call path allows.
  • Scan/recovery lookahead remains covered by tests.
  • Locked wallet behavior remains compatible with existing cached-key semantics.
  • Explicit keypoolrefill remains the operator-controlled full refill path.
  • Bench or log evidence shows this path no longer reintroduces the large P2MR DB/keygen timesink during normal marked-used handling.

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions