Repository navigation
Description
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.pyis the report-only RPC benchmark harness.test/functional/data/rpc_perf_manifest.jsonincludes several wallet RPC cases, but notgetnewaddress.contrib/devtools/bench_wallet_create.pytimes first receive/change address generation, but no checked-in CSV baseline was found.src/libbitcoinpqc/benches/REPORT.mdrecords bounded SLH-DSA-SHA2-128s keygen at about11.7 ms/opon 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:getnewaddressRPC pathsrc/wallet/interfaces.cpp: GUI/interface receive-address pathsrc/wallet/wallet.cpp:CWallet::GetNewDestination, scheduled wallet worksrc/wallet/scriptpubkeyman.cpp:DescriptorScriptPubKeyMan::GetNewDestination, keypool top-up, descriptor writessrc/wallet/walletdb.cppandsrc/wallet/sqlite.cpp: wallet DB writes and transaction behaviorsrc/libbitcoinpqc: PQC key generation cost
Current P2MR receive-address cost path:
getnewaddressCWallet::GetNewDestination- external
DescriptorScriptPubKeyMan::GetNewDestination - keypool
TopUp() - P2MR descriptor expansion and PQC private-key persistence
- descriptor
next_indexwrite - 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:
- Keep current keypool behavior for non-P2MR descriptors.
- Keep current behavior for non-ranged descriptors.
- In
DescriptorScriptPubKeyMan::GetNewDestination, skip ordinary full keypool maintenance for ranged P2MR descriptors while cached entries remain. - Preserve the existing
TopUp(1)fallback whennext_index >= range_end. - Add descriptor helpers for:
- ranged P2MR detection
- remaining keypool size
- low-watermark calculation
- refill-needed state
- bounded refill target
- Add wallet-level scheduled refill state so only one P2MR receive refill worker runs per wallet.
- Trigger scheduling after successful P2MR receive-address generation from:
getnewaddress- wallet interfaces used by GUI address generation
- Run refill in bounded steps through the existing top-up transaction path.
- Preserve explicit
keypoolrefillas 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
keypoolrefillbehavior. - 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_enddoes 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
getnewaddressno 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
keypoolrefillstill 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
getnewaddressno 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=INFOBefore pushing, run the repository lint command through Docker.
Activity