Skip to content

Avoid synchronous P2MR keypool maintenance in getnewaddress #26

Closed

Description

@kiwidream

Summary

getnewaddress can be slow for ranged P2MR wallets because the receive-address path can synchronously maintain a full keypool before returning an address.

For P2MR descriptors, keypool top-up is materially more expensive than ordinary ECDSA/Schnorr keypool maintenance: it can derive PQC private key material, update descriptor cache state, persist P2MR private-key records, write descriptor state, and then write the address book entry.

Change the P2MR receive-address path so ordinary getnewaddress calls return already-persisted keypool entries quickly, and refill the external P2MR keypool only when it reaches a conservative low-watermark.

Impact

On P2MR-only chains, default wallet receive addresses are P2MR. In steady state, a wallet can therefore pay P2MR key derivation and wallet DB write costs during ordinary address generation.

This creates user-visible latency and increases wallet DB write contention for an RPC that should usually be served from pre-generated keypool entries.

The issue is performance and reliability hardening. It is not evidence that generated P2MR addresses are incorrect.

Evidence

Local investigation found no checked-in promoted getnewaddress benchmark result:

  • test/functional/feature_rpc_perf.py is the report-only RPC benchmark harness.
  • test/functional/data/rpc_perf_manifest.json includes several wallet RPC cases, but not getnewaddress.
  • contrib/devtools/bench_wallet_create.py times first receive/change address generation, but no checked-in CSV baseline was found.
  • src/libbitcoinpqc/benches/REPORT.md records bounded SLH-DSA-SHA2-128s keygen at about 11.7 ms/op on Apple M3 Max, before wallet DB writes or lock contention.

The likely cost is not address encoding. It is replacement P2MR key derivation and persistence done to keep the keypool full on the address-generation path.

Source Trace

Relevant areas:

  • src/wallet/rpc/addresses.cpp: getnewaddress RPC path
  • src/wallet/interfaces.cpp: GUI/interface receive-address path
  • src/wallet/wallet.cpp: CWallet::GetNewDestination, scheduled wallet work
  • src/wallet/scriptpubkeyman.cpp: DescriptorScriptPubKeyMan::GetNewDestination, keypool top-up, descriptor writes
  • src/wallet/walletdb.cpp and src/wallet/sqlite.cpp: wallet DB writes and transaction behavior
  • src/libbitcoinpqc: PQC key generation cost

Current P2MR receive-address cost path:

  1. getnewaddress
  2. CWallet::GetNewDestination
  3. external DescriptorScriptPubKeyMan::GetNewDestination
  4. keypool TopUp()
  5. P2MR descriptor expansion and PQC private-key persistence
  6. descriptor next_index write
  7. address book write

Fresh P2MR wallet creation already uses a small warm keypool and deferred background top-up. The slow path remains possible in steady-state address generation after deferred top-up completes.

Expected Behavior

For ranged P2MR descriptors, getnewaddress should normally return an address from already-persisted keypool state without synchronously replenishing the full keypool first.

When the external P2MR receive keypool reaches a low-watermark, the wallet should start bounded refill work in the background where scheduler context is available.

If the keypool is actually exhausted, unlocked wallets may keep the existing one-address synchronous fallback. Locked encrypted wallets should continue returning cached entries while available and should fail with the existing keypool-ran-out behavior only at exhaustion.

Proposed Fix

Use a low-watermark refill policy for ranged P2MR receive descriptors.

Suggested low-watermark:

low_watermark = std::min<int64_t>(
    m_keypool_size,
    std::max<int64_t>(DEFAULT_CREATE_WALLET_P2MR_WARM_KEYPOOL, m_keypool_size / 10));

Suggested refill step target:

next_target = std::min<int64_t>(
    m_keypool_size,
    current_remaining + DEFAULT_CREATE_WALLET_P2MR_WARM_KEYPOOL);

Implementation shape:

  1. Keep current keypool behavior for non-P2MR descriptors.
  2. Keep current behavior for non-ranged descriptors.
  3. In DescriptorScriptPubKeyMan::GetNewDestination, skip ordinary full keypool maintenance for ranged P2MR descriptors while cached entries remain.
  4. Preserve the existing TopUp(1) fallback when next_index >= range_end.
  5. Add descriptor helpers for:
    • ranged P2MR detection
    • remaining keypool size
    • low-watermark calculation
    • refill-needed state
    • bounded refill target
  6. Add wallet-level scheduled refill state so only one P2MR receive refill worker runs per wallet.
  7. Trigger scheduling after successful P2MR receive-address generation from:
    • getnewaddress
    • wallet interfaces used by GUI address generation
  8. Run refill in bounded steps through the existing top-up transaction path.
  9. Preserve explicit keypoolrefill as the operator-controlled full refill path.

Background refill should not hold the wallet DB write semaphore while waiting for descriptor locks. Keep descriptor/DB lock ordering consistent with foreground address reservation to avoid introducing lock-order deadlocks.

Safety Requirements

  • Never return a P2MR address unless its descriptor cache and private P2MR key material were already persisted, or a synchronous fallback top-up has just persisted them successfully.
  • Do not change non-P2MR keypool semantics.
  • Do not change explicit keypoolrefill behavior.
  • Do not run low-watermark background refill while create-time deferred top-up is still pending.
  • Do not schedule duplicate refill workers for the same wallet.
  • Preserve locked encrypted wallet behavior:
    • cached P2MR entries continue to work while available;
    • background refill does not make a locked wallet fail early;
    • actual exhaustion returns the existing keypool-ran-out error.
  • Keep top-up persistence and rollback behavior centralized in the existing descriptor top-up transaction path.
  • Avoid logging on every fast-path address generation call; log scheduled refill failures with descriptor id, target, remaining count, and error string.
  • Keep change-address and transaction funding behavior conservative unless separately covered by tests.

Suggested Tests

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

  • P2MRGetNewAddressDoesNotTopUpAboveLowWatermark

    • Complete P2MR keypool top-up.
    • Generate receive addresses while remaining entries are above the low-watermark.
    • Assert keypool size decreases and range_end does not advance.
  • P2MRGetNewAddressSchedulesLowWatermarkRefill

    • Drain the external P2MR receive pool to the low-watermark.
    • Trigger scheduling from the address-generation path.
    • Advance the scheduler.
    • Assert refill occurs in bounded steps and eventually restores the configured keypool size.
  • P2MRGetNewAddressFallbackTopUpAtExhaustionWithoutScheduler

    • Use a path without scheduler context.
    • Drain the external P2MR receive pool.
    • Assert an unlocked wallet can still return one more address through the one-address fallback.
  • LockedEncryptedP2MRWalletUsesCachedKeysBelowLowWatermark

    • Use an encrypted locked P2MR wallet.
    • Drain below the low-watermark.
    • Assert cached receive addresses still work.
    • Assert exhaustion returns the existing keypool-ran-out error.

Also consider raw-change coverage if getrawchangeaddress is changed in the same patch:

  • raw change calls should be able to skip inline low-watermark refill;
  • normal transaction change reservation should retain a conservative bounded fallback;
  • actual exhaustion should still use the one-address fallback for unlocked wallets.

Functional and regression coverage to run:

  • wallet_keypool_topup.py
  • focused P2MR wallet unit tests
  • locked encrypted P2MR wallet tests
  • deferred create-time P2MR keypool tests

Acceptance Criteria

  • Ranged P2MR getnewaddress no longer performs synchronous full keypool maintenance while cached keypool entries remain.
  • External P2MR receive refill starts at or below the low-watermark and proceeds in bounded background steps.
  • Empty-pool fallback behavior remains available for unlocked wallets.
  • Locked encrypted wallets keep using cached P2MR entries below the low-watermark and fail only at exhaustion.
  • Non-P2MR descriptors retain existing top-up behavior.
  • Explicit keypoolrefill still fills to the requested target.
  • Background refill does not introduce descriptor/DB lock-order deadlocks.
  • Tests cover above-watermark, low-watermark, no-scheduler fallback, and locked encrypted behavior.
  • Benchmark or log evidence shows ordinary P2MR getnewaddress no longer pays replacement PQC keygen and full top-up DB write cost on every successful address call.

Reverify Requirement

Run:

cmake --build build --target test_bitcoin qbitd qbit-cli -j8
build/bin/test_qbit '--run_test=wallet_tests/P2MRGetNewAddress*'
build/bin/test_qbit '--run_test=wallet_tests/P2MRGetNewChangeAddress*'
build/bin/test_qbit '--run_test=wallet_tests/*DeferredP2MR*'
build/bin/test_qbit '--run_test=wallet_tests/LockedEncryptedP2MRWalletUsesCachedKeysBelowLowWatermark'
build/bin/test_qbit '--run_test=wallet_tests/LockedEncryptedP2MRWalletUsesCachedChangeKeysBelowLowWatermark'
build/bin/test_qbit '--run_test=wallet_tests/KeypoolTopUpReportsLockedInternalP2MRDescriptorFailure'
build/test/functional/wallet_keypool_topup.py --timeout-factor=0.5 --loglevel=INFO

Before pushing, run the repository lint command through Docker.

Activity

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

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