Skip to content

wallet: make descriptor SPKM mutex non-recursive - #35444

Open
w0xlt wants to merge 4 commits into
bitcoin:masterfrom
w0xlt:wallet-descriptor-spkm-mutex-19303-simple-index
Open

w0xlt wants to merge 4 commits into
bitcoin:masterfrom
w0xlt:wallet-descriptor-spkm-mutex-19303-simple-index

Conversation

@w0xlt

@w0xlt w0xlt commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Part of #19303

This PR makes DescriptorScriptPubKeyMan use a non-recursive private mutex by moving locking responsibility into its public methods and using lock-held internal helpers for shared logic.

The change removes external locking of DescriptorScriptPubKeyMan::cs_desc_man, splits recursive internal call paths such as keypool top-up and descriptor updates, and then renames the mutex to m_desc_mutex.

No wallet database format, RPC behavior, keypool semantics, or external signer behavior is intended to change.

@DrahtBot DrahtBot added the Wallet label Jun 2, 2026
@DrahtBot

DrahtBot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

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.

Type Reviewers
ACK pablomartin4btc
Concept ACK hebasto, polespinasa

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:

  • #36885 (wallet, rpc: Add analyzedescriptor for multisig setups by pablomartin4btc)
  • #36154 (wallet: fill PSBT_GLOBAL_XPUB by jeanpablojp)
  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)
  • #35998 (wallet: Handle or explicitly ignore WalletBatch write failures by achow101)
  • #35429 (wallet: avoid global access in external signer SPKM by w0xlt)
  • #35302 (Silent Payments: Sending (take 2) by Eunovo)
  • #34969 (fuzz: several improvements to scriptpubkeyman harness by brunoerg)
  • #34520 (refactor: Add [[nodiscard]] to functions returning bool+mutable ref by maflcko)

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.

LLM Linter (✨ experimental)

Possible internal implementation names in log messages:

  • src/wallet/scriptpubkeyman.cpp: WalletLogPrintf("%s: Detected a used keypool item at index %d, ...", __func__, index) → Remove __func__; function identification is redundant with -logsourcelocations.
  • src/wallet/scriptpubkeyman.cpp: WalletLogPrintf("%s: Topping up keypool failed (locked wallet)", __func__) → Remove __func__; function identification is redundant with -logsourcelocations.

2026-10-30 00:40:51

@pablomartin4btc pablomartin4btc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK.

I reviewed the commits individually. The split between public self-locking methods and lock-held helpers makes sense to me, and the external lock removals seem correct now that descriptor accessors return/ use state under their own lock. I left one question around listdescriptors, where two descriptor reads are now done through separate self-locking calls instead of under one caller-held lock, and a minor readability suggestion regarding the cs_desc_man lock removal in addhdkey().

Comment thread src/wallet/scriptpubkeyman.cpp Outdated
return op_dest;
LOCK(m_desc_mutex);
auto dest{GetNewDestination_(type)};
if (dest) index = m_wallet_descriptor.next_index - 1;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice cleanup: this avoids updating index after a failed destination request.

Comment thread src/wallet/rpc/backup.cpp Outdated
@@ -544,7 +544,6 @@ RPCMethod listdescriptors()
if (!desc_spk_man) {
throw JSONRPCError(RPC_WALLET_ERROR, "Unexpected ScriptPubKey manager type.");
}
LOCK(desc_spk_man->cs_desc_man);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think removing the external lock here is fine now that GetWalletDescriptor() and GetDescriptorString() are self-locking. One subtle difference is that the descriptor metadata and descriptor string are now read under two separate locks instead of one caller-held lock. I don’t see an issue because descriptor state should not normally change concurrently here, but I wanted to double-check that no atomicity across these two reads was intended.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I also think it is safe because listdescriptors holds wallet->cs_wallet across both calls. Any update that could change either the descriptor metadata or descriptor string also needs cs_wallet, so it cannot run between those two reads.

Comment thread src/wallet/rpc/wallet.cpp Outdated
@@ -905,7 +904,6 @@ RPCMethod addhdkey()

UniValue response(UniValue::VOBJ);
const DescriptorScriptPubKeyMan& desc_spkm = spkm->get();
LOCK(desc_spkm.cs_desc_man);
std::set<CPubKey> pubkeys;
std::set<CExtPubKey> extpubs;
desc_spkm.GetWalletDescriptor().descriptor->GetPubKeys(pubkeys, extpubs);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very minor readability nit: would it be clearer to first store the result of GetWalletDescriptor() in a local variable and then call GetPubKeys() on it? That would make it more obvious that the operation is performed on a copied descriptor returned by the accessor, rather than directly on internal SPKM state.

Suggested change
desc_spkm.GetWalletDescriptor().descriptor->GetPubKeys(pubkeys, extpubs);
auto wallet_descriptor = desc_spkm.GetWalletDescriptor(); // locks internally, returns copy
wallet_descriptor.descriptor->GetPubKeys(pubkeys, extpubs); // operates on the copy

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Thanks.

@hebasto hebasto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK.

@w0xlt

w0xlt commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

Rebased.

@w0xlt
w0xlt force-pushed the wallet-descriptor-spkm-mutex-19303-simple-index branch from f762354 to 2bd9f4d Compare June 20, 2026 08:27
@sedited

sedited commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Ping for rebase @w0xlt

@w0xlt
w0xlt force-pushed the wallet-descriptor-spkm-mutex-19303-simple-index branch from 2bd9f4d to 4bb39d5 Compare September 15, 2026 22:11
@w0xlt
w0xlt force-pushed the wallet-descriptor-spkm-mutex-19303-simple-index branch from 4bb39d5 to 56ca23f Compare September 15, 2026 22:25
@w0xlt
w0xlt force-pushed the wallet-descriptor-spkm-mutex-19303-simple-index branch from 56ca23f to b6d5866 Compare September 15, 2026 22:44
@w0xlt

w0xlt commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Rebased.

@polespinasa polespinasa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

concept ACK 3d5e077

Comment thread src/wallet/scriptpubkeyman.cpp Outdated
index = m_wallet_descriptor.GetNext() - 1;
return op_dest;
auto dest{GetNewDestination_(type)};
if (dest) index = m_wallet_descriptor.GetNext() - 1;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in 2f2cc56 wallet: split descriptor SPKM locked internals

The commit message claims there is no behavior change in this commit, but this is indeed a behavior change as now it only writes the index on success, before it was writing it in success and in case of failure.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Thanks.

}

// TopUp
spkm->TopUpWithDB(batch);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in dadc205 wallet: stop locking descriptor SPKM externally

After removing this line, no one uses TopUpWithDB anymore. Maybe could also remove the protected wrapper?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Thanks.

{
LOCK(cs_desc_man);
std::string error;
if (!CanUpdateToWalletDescriptor(descriptor, error)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in 2f2cc56 wallet: split descriptor SPKM locked internals

After removing this, CanUpdateToWalletDescriptor is only used by a fuzz test, but not real code. Consider removing the function entirely.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Thanks.

@w0xlt
w0xlt force-pushed the wallet-descriptor-spkm-mutex-19303-simple-index branch from 3d5e077 to f3bad2b Compare October 6, 2026 19:50
@DrahtBot

DrahtBot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task OpenBSD Cross: https://github.com/bitcoin/bitcoin/actions/runs/37521939038/job/112469290765
LLM reason (✨ experimental): CI failed during compilation: scriptpubkeyman.cpp references the undeclared identifier cs_desc_man.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

Comment thread src/wallet/scriptpubkeyman.cpp Outdated
}
changed = before != CanGetAddresses_();
}
if (changed) NotifyCanGetAddressesChanged();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in 04b7fc1 wallet: make descriptor SPKM mutex non-recursive

Correct me if I am wrong, but SetupDescriptorGeneration, SetupDescriptor and UpdateWithSigningProvider run before the new constructed SPKM is returned so they don't have any signal subscribers yet. This makes calling NotifyCanGetAddressesChanged useless.
Because of that all the change detection logic calling CanGetAddresses_() is also unecessary.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Thanks.

@w0xlt
w0xlt force-pushed the wallet-descriptor-spkm-mutex-19303-simple-index branch from 5426d8d to 2811f44 Compare October 7, 2026 23:11
@w0xlt
w0xlt force-pushed the wallet-descriptor-spkm-mutex-19303-simple-index branch from 2811f44 to b38237f Compare October 8, 2026 23:25
@w0xlt

w0xlt commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Rebased

@pablomartin4btc pablomartin4btc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK b38237f

Thanks for taking the suggestions.

Verified @polespinasa's feedback is properly addressed and code rebased.

Left a non-blocking comment.

BOOST_CHECK(!spkm->GetReservedDestination(OutputType::BECH32, /*internal=*/false, index));
BOOST_CHECK_EQUAL(index, -1);
check_notifications({});
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing, non-blocking: in b3f2503 ("wallet: make descriptor SPKM mutex non-recursive"), in desc_spkm_availability_notifications, the sub-test exercising UpdateWalletDescriptor() throwing mid-top-up and still firing a notification before rethrowing (failed_descriptor.SetEnd(5) / HasReason("Could not top up scriptPubKeys") / check_notifications({true})) is gone — was dropping this coverage intentional?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks. It was dropped unintentionally while addressing #35444 (comment).

w0xlt added 4 commits October 29, 2026 16:33
Prepare DescriptorScriptPubKeyMan for making cs_desc_man non-recursive by
separating public lock-taking entry points from helpers that require
cs_desc_man to already be held.

This removes recursive calls from the core descriptor paths. The public
mutex remains recursive and externally accessible in this commit, so
existing call sites continue to build while locked helpers centralize the
shared logic used by keypool top-up, descriptor updates, address generation,
and descriptor matching.

Remove the public CanUpdateToWalletDescriptor wrapper, which is only used
by the fuzz harness. Have the harness call UpdateWalletDescriptor under
cs_wallet so updates exercise the same validation as production callers.

GetReservedDestination() now sets the output index only when destination
creation succeeds, leaving it unchanged on failure. Existing wallet callers
already ignore this output on failure, so their behavior is unchanged.
Move the remaining descriptor SPKM callers to self-locking public methods
instead of taking cs_desc_man directly. This removes direct locks from wallet,
RPC, and fuzz code and lets DescriptorScriptPubKeyMan own synchronization for
its descriptor state.

External signer wallet creation also stops mutating m_wallet_descriptor under
a direct external lock. It now calls SetupDescriptor, which performs the same
descriptor write and top-up sequence behind the SPKM API.

Remove the now-unused protected TopUpWithDB wrapper. Internal callers
continue to use the lock-held TopUpWithDB_ helper.

The mutex remains recursive and public in this commit, so this is a call-site
cleanup that sets up the final non-recursive conversion without changing
wallet behavior.
Make cs_desc_man private and replace RecursiveMutex with Mutex. Annotate
self-locking entry points with negative lock requirements and retain
LOCKS_EXCLUDED on factory-only setup methods.

Move address-availability notifications to outer operations on existing
SPKMs. Compare availability before and after each operation under the
mutex, then notify after unlocking so synchronous callbacks can query the
wallet safely. Notify only for a net change and rethrow captured exceptions
after notification.

Factory initialization takes the mutex without change tracking or
notifications, since newly constructed SPKMs have no signal subscribers.

Add a watch-only hardened-descriptor regression test covering synchronous
callback re-entry, address consumption and return, range extension,
unchanged availability, and partial failures.
Now that DescriptorScriptPubKeyMan::cs_desc_man is a non-recursive, private
Mutex, rename it to m_desc_mutex to match the member-mutex naming convention
adopted by the other RecursiveMutex->Mutex conversions. No behavior change.

-BEGIN VERIFY SCRIPT-
sed -i 's/cs_desc_man/m_desc_mutex/g' $(git grep -l cs_desc_man -- '*.cpp' '*.h')
-END VERIFY SCRIPT-

@pablomartin4btc pablomartin4btc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re-ACK 2cde6f9

Since my last review: rebased (I've verified that range-diff shows only the trailing-newline log fixes required after #36397), plus the restored UpdateWalletDescriptor() failing-top-up sub-test in desc_spkm_availability_notifications (thanks for addressing #35444 (comment)).

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants