Skip to content

net: encapsulate TxRelay state and replace recursive mutexes - #34824

Open
w0xlt wants to merge 6 commits into
bitcoin:masterfrom
w0xlt:refactor/replace-txrelay-recursive-mutexes
Open

w0xlt wants to merge 6 commits into
bitcoin:masterfrom
w0xlt:refactor/replace-txrelay-recursive-mutexes

Conversation

@w0xlt

@w0xlt w0xlt commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor

Part of #19303.

This PR refactors per-peer transaction relay state so TxRelay owns its guarded data and lock boundaries before replacing its RecursiveMutex members with plain Mutex.

Before this change, Peer::TxRelay was mostly a collection of public state inside net_processing.cpp.
Callers directly locked its mutexes, inspected its fields, and mutated its containers.
That made the mutex type change hard to review: replacing RecursiveMutex with Mutex is only clearly safe if outside code cannot accidentally recurse, take locks in the wrong order, or bypass the intended state transitions.

The main changes are:

  • Move Peer::TxRelay into node::TxRelay.
  • Route bloom-filter and transaction-inventory state changes through named TxRelay methods.
  • Remove direct TxRelay field and mutex access from net_processing.cpp.
  • Snapshot queued transaction inventory into a TxInventoryBatch in SendMessages(), process it without holding the TxRelay mutex, and merge unsent entries back afterward.
  • Hide the batch backing storage behind a small semantic API.
  • Add unit tests and a fuzz target for the extracted TxRelay behavior.
  • Replace the two RecursiveMutex members with Mutex and annotate the inventory-before-bloom lock order.

No P2P behavior change is intended. The purpose is to move from "external code locks and mutates TxRelay internals" to "TxRelay owns its state transitions and locking contract."

The most important commit to review is the SendMessages() batch snapshot refactor, because that is where the lock ownership model changes. The final mutex replacement is intentionally small after the state has been encapsulated.

@DrahtBot DrahtBot added the P2P label Mar 14, 2026
@DrahtBot

DrahtBot commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/34824.

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK hebasto, theuni
Stale ACK sedited, pablomartin4btc

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:

  • #36607 (private broadcast: Extra guard against unintended non-private broadcast of private transactions by optout21)
  • #35874 (p2p: prevent BIP35 requesters from bypassing inbound tx-relay capacity by l0rinc)
  • #35591 ([DO NOT MERGE] Erlay: bandwidth-efficient transaction relay protocol (Full implementation) by sr-gi)
  • #35522 (refactor: Extract per-message helpers from SendMessages() (move-only) by pablomartin4btc)
  • #35502 (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)

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 places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • CBloomFilter{10, 0.001, 0, BLOOM_UPDATE_NONE} in src/test/txrelay_tests.cpp
  • CBloomFilter{10, 0.001, 0, BLOOM_UPDATE_ALL} in src/test/txrelay_tests.cpp

2026-09-15 20:05:05

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Concept ACK

I looked this over and also didn't find any cases where locking recursion would be required, but the change seems brittle to me. Not sure if just changing these is the best way to handle this.

@w0xlt
w0xlt force-pushed the refactor/replace-txrelay-recursive-mutexes branch from ed2a83c to 8ed9eb0 Compare March 15, 2026 18:51
@w0xlt

w0xlt commented Mar 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @sedited for the feedback.

The original PR intentionally included only the first commit to avoid non-trivial refactoring and focus on the RecursiveMutex conversion. After your concerns that this minimal approach might be brittle, I took a second pass.

A broader refactor seems justified: both TxRelay and net_processing benefit from clearer separation of concerns and improved modularization. The main changes are:

  • TxRelay is now a dedicated component in src/node/txrelay.h, instead of being embedded in src/net_processing.cpp.

  • SendMessages() and related call sites now use intent-named operations (ConsumeSendMempool, SetNextInvSendTime, TxInventoryKnownInsert, etc.) rather than mutating fields directly, which reduces local complexity.

  • Locking contracts are now explicit at API boundaries (EXCLUSIVE_LOCKS_REQUIRED, LOCK_RETURNED), improving static thread-safety checking and reviewability.

  • State transitions/invariants are centralized in TxRelay methods (PushInventory, VerifyInventoryPristine, ClearTxInventoryToSendIfNoRelayTxs), reducing the risk of missed field updates.

  • Lock-order reasoning is clearer because lock acquisition sites are now structured and annotated rather than scattered raw member-lock uses.

  • Future changes to TxRelay internals (containers/fields) should require fewer net-processing edits, since call sites depend more on behavior methods than storage details.

@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.

Replace m_bloom_filter_mutex and m_tx_inventory_mutex in Peer::TxRelay from RecursiveMutex to Mutex.

Concept ACK.

@theuni

theuni commented Mar 18, 2026

Copy link
Copy Markdown
Member

Concept ACK.

Lock-order reasoning is clearer because lock acquisition sites are now structured and annotated rather than scattered raw member-lock uses.

See also the ACQUIRED_BEFORE/ACQUIRED_AFTER annotations which may be useful when there's an established ordering that should be followed.

(Note that unless -Wthread-safety-beta is used, clang 22 is required to actually see the warnings: llvm/llvm-project#152853)

@fanquake

Copy link
Copy Markdown
Member

(Note that unless -Wthread-safety-beta is used, clang 22 is required to actually see the warnings: llvm/llvm-project#152853)

(also note that we currently use Clang 22.1.2 in the CI)

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approach ACK

I think I prefer this over a bare bones mutex type change. The changes in the first four commits are pretty straight forward and make sense to me. The last commit is a bit more involved, but git color coding the moved bits does help a bit. I'd be curious to see what others think.

Comment thread src/node/txrelay.h Resolved
@w0xlt
w0xlt force-pushed the refactor/replace-txrelay-recursive-mutexes branch from 8ed9eb0 to 475366b Compare March 24, 2026 20:58
@w0xlt

w0xlt commented Mar 24, 2026

Copy link
Copy Markdown
Contributor Author

ACQUIRED_BEFORE/ACQUIRED_AFTER annotations added. Tested with clang 18 and -Wthread-safety-beta.

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK 475366b

I'm not sure about the last commit. It is a bit noisy, but I also like the additional assurances and encapsulation.

Comment thread src/net_processing.cpp Resolved
Comment thread src/node/txrelay.h Resolved
Comment thread src/node/txrelay.h Resolved
@DrahtBot
DrahtBot requested review from hebasto and theuni May 3, 2026 13:26
@w0xlt
w0xlt force-pushed the refactor/replace-txrelay-recursive-mutexes branch from 475366b to 67527c7 Compare May 17, 2026 07:33

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

re-ACK 67527c70975e1c3bb4918ba0ebeb4313d8c741be

@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. The first commits look straightforward (as said earlier), and commit 5 seems to preserve the existing lock order while moving the remaining TxRelay state access in SendMessages() behind annotated helpers.

Non-blocking/ follow-up idea: after this PR, it may be worth considering a small refactor of the tx-relay section of SendMessages(). The code could maybe be split into a few conceptual helpers for periodic relay scheduling, BIP35 mempool responses, and regular tx-inventory relay selection. I would not suggest perhaps one helper per comment/ filter condition, but grouping those areas into conceptual helpers could make SendMessages() cleaner and easier to follow, while keeping the change behaviour-preserving.

@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 67527c7.

Checked both m_bloom_filter_mutex and m_tx_inventory_mutex in Peer::TxRelay aren't acquired recursively, makes sense to move them into non-recursive mutexes (the 18 lock sites mentioned in the description are enumerated in the first commit body for reference).

The PR introduces ACQUIRED_BEFORE(m_tx_inventory_mutex) on m_bloom_filter_mutex (and ACQUIRED_AFTER on the other side) - as suggested. This establishes a lock ordering that didn't exist before, that ordering annotation becomes load-bearing for deadlock prevention, not just documentation.

Also, reviewed the replacement of direct member access to TxRelay internals with accessor methods. Members are now private — the only access path is through accessors that either self-lock (negative capability !mutex) or require the caller to hold the lock, with Clang TSA enforcing both at compile time.

@maflcko maflcko 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.

Comment thread src/net_processing.cpp Outdated
@@ -925,7 +925,7 @@ class PeerManagerImpl final : public PeerManager

/** Determine whether or not a peer can request a transaction, and return it (or nullptr if not found or not allowed). */
CTransactionRef FindTxForGetData(const Peer::TxRelay& tx_relay, const GenTxid& gtxid)
EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, !tx_relay.m_tx_inventory_mutex);
EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, !tx_relay.GetTxInventoryMutex());

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.

05b3bbcb0e2b7d66a8107c26b837cb68f4eb5dc0: idk, what is the point of this pull request?

Just changing a RecursiveMutex to a Mutex without proper TSA doesn't make sense, imo. This just risks unsafe code down the line in the future.

This pull is now moving locking to happen in different files/classes, and still exposes the mutex field globally, just like before.

I don't see how this makes anything safer/easier.

Either, this should be done properly or not at all. I know this isn't easy, which is probably why it hasn't been done for such a long time, but that shouldn't be an excuse to do it improperly.

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.

Updated. Direct TxRelay data access is gone and state changes now go through TSA-annotated helpers. The remaining mutex accessors are kept for the existing SendMessages() batching/lock-order annotations.

Comment thread src/node/txrelay.h Outdated
{
LOCK(m_bloom_filter_mutex);
if (!m_bloom_filter) return false;
callable(*m_bloom_filter);

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.

05b3bbcb0e2b7d66a8107c26b837cb68f4eb5dc0: Is this pattern even safe?

Does clang TSA detect if callable were to lock the mutex and thus lead to UB?

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. Removed this callback pattern. The filtered-block path now uses TxRelay::MakeMerkleBlock() instead.

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 the pattern could work, but only if the mutex getter is not defined and only exists to provide compile-time annotations: #19303 (comment)

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.

Thanks, that makes sense.
The current version no longer has the public mutex getter or the callback-under-lock pattern.
The filtered block path now uses TxRelay::MakeMerkleBlock(), and the mutexes are not exposed, so I think this concern is now addressed.

@w0xlt

w0xlt commented Jun 13, 2026

Copy link
Copy Markdown
Contributor Author

Update after the latest changes:

The specific callback/TSA concern raised above has been addressed: WithBloomFilterIfSet() was removed, and the filtered-block path now uses TxRelay::MakeMerkleBlock(), so CMerkleBlock construction happens directly under TxRelay's bloom-filter mutex without passing an arbitrary callable while the mutex is held.

The broader goal here is not just “remove RecursiveMutex” for its own sake. The intent is to make the locking logic easier to follow. Compared to the original minimal mutex-type change, the current branch now:

  • moves TxRelay into its own component,
  • makes the guarded data private,
  • routes state transitions through named, TSA-annotated methods,
  • documents/enforces the m_tx_inventory_mutex -> m_bloom_filter_mutex lock order,
  • adds unit coverage and a fuzz target for the extracted TxRelay behavior.

There is still some intentional mutex exposure through GetBloomFilterMutex() / GetTxInventoryMutex() because SendMessages() currently batches work while holding locks across multiple relay-policy steps.

I think keeping that structure avoids a larger behavioral refactor in this PR, while still making the existing locking more explicit and reviewable.

This should make future follow-ups easier, since TxRelay state transitions are now centralized, annotated, and independently tested.

@w0xlt

w0xlt commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

Regarding the new txrelay fuzz target, it exercises the public TxRelay API while tracking the expected relay state and checking TxRelay against it after each operation.

It covers bloom-filter lifecycle, merkle-block creation, known-inventory handling, queued announcement drain/erase paths, BIP35 mempool one-shot handling, fee-filter, and sequence bookkeeping while accounting for rolling-bloom false positives.

@maflcko

maflcko commented Jun 15, 2026

Copy link
Copy Markdown
Member

The broader goal here is not just “remove RecursiveMutex” for its own sake. The intent is to make the locking logic easier to follow. Compared to the original minimal mutex-type change, the current branch now:

* moves `TxRelay` into its own component,

* makes the guarded data private,

* routes state transitions through named, TSA-annotated methods,

* documents/enforces the `m_tx_inventory_mutex -> m_bloom_filter_mutex` lock order,

* adds unit coverage and a fuzz target for the extracted `TxRelay` behavior.

There is still some intentional mutex exposure through GetBloomFilterMutex() / GetTxInventoryMutex() because SendMessages() currently batches work while holding locks across multiple relay-policy steps.

Yeah, and those aren't check with Clang TSA, are they? I am just not convinced that moving to a non-recursive mutex is useful, when it is less safe and requires manual review to avoid UB.

All of the changes you list have nothing to do with the mutex change. It is possible to do all of the changes independently while keeping the recursive mutex.

Some of the changes are required to make the mutex non-recursive, but I don't think they are sufficient. IIUC making the data and the mutex private (and not exposing references to them) are required changes. However, by exposing references to them in a public getter, those changes are basically undone.

I know this pattern may not have been followed in the past (in #19303 related pulls and elsewhere), but I think there is value in first defining a set of possible safe code patterns, and then apply them consistently and consequently. IIUC the pattern is that non-recursive mutexes can be used for fully private fields and that recursive mutexes should be used for globals/public fields? If so, then I think mixing the patterns does not make sense.

@w0xlt
w0xlt force-pushed the refactor/replace-txrelay-recursive-mutexes branch from dab04e0 to 73d972b Compare June 16, 2026 18:45
@w0xlt w0xlt changed the title net: refactor: replace Peer::TxRelay RecursiveMutex instances with Mutex net: encapsulate TxRelay state and replace recursive mutexes Jun 16, 2026
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/27640198801/job/81737890148
LLM reason (✨ experimental): CI failed at compile time because src/test/txrelay_tests.cpp references private members of node::TxRelay (e.g., m_tx_inventory_mutex, m_next_inv_send_time, m_send_mempool), causing clang++ errors.

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.

@w0xlt
w0xlt force-pushed the refactor/replace-txrelay-recursive-mutexes branch from 73d972b to d88df07 Compare June 17, 2026 17:25
@w0xlt

w0xlt commented Jun 17, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback. The concern is valid.

The original goal of this PR was fairly small, just replacing those variables with Mutex, and I was trying to keep the change scoped and avoid a larger TxRelay refactor.

To address the mutex exposure issue, I reworked the branch so that encapsulation comes first, with the mutex replacement as the final step.

The public mutex accessors have been removed, the guarded state is now private, and net_processing.cpp no longer locks or mutates TxRelay internals directly.

The SendMessages() path now uses an opaque TxInventoryBatch to snapshot and retrieve queued inventory from TxRelay.

I updated the PR title and description to better reflect the current scope. The PR has evolved beyond a simple mutex replacement and now introduces a new networking component.

@w0xlt

w0xlt commented Jun 17, 2026

Copy link
Copy Markdown
Contributor Author

Unrelated CI error

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/27707284284/job/82331997608
LLM reason (✨ experimental): CI failed to build the fuzz target because src/test/fuzz/txrelay.cpp tries to access private node::TxRelay members (m_tx_inventory_mutex, m_send_mempool, m_next_inv_send_time), producing compilation errors under -Werror.

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.

@sedited

sedited commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

I think there is a silent merge conflict here.

@w0xlt
w0xlt force-pushed the refactor/replace-txrelay-recursive-mutexes branch 2 times, most recently from 5a34f55 to e8dbc6e Compare July 1, 2026 00:52
@DrahtBot DrahtBot removed the CI failed label Jul 1, 2026
@w0xlt

w0xlt commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

Rebased. Thanks

@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 e8dbc6e

Since my last ACK: WithBloomFilterIfSet() and the public mutex getter were removed - addressing maflcko's concerns that exposing the mutex reference undoes the TSA safety guarantees. State changes now go exclusively through EXCLUSIVE_LOCKS_REQUIRED(!mutex) annotated helpers, and MakeMerkleBlock() replaces the callable-under-lock pattern.

@DrahtBot
DrahtBot requested a review from sedited July 1, 2026 21:13
Move the per-peer transaction relay state and helper methods out of
net_processing.cpp into a new node::TxRelay type.

Keep the existing locking model and behavior intact while giving the
transaction relay code a single home. Net processing still owns
the relay flow. This commit only moves the state, bloom-filter
helpers, and inventory helpers so later commits can tighten the
interface without mixing in behavior changes.
Move the remaining SendMessages transaction-inventory access behind
TxRelay methods.

StartTxInventoryBatch() snapshots queued inventory while holding the
TxRelay mutex, lets SendMessages drain the batch without holding that
mutex, and ReturnTxInventory() merges unsent entries back into the live
queue.

This removes the remaining direct TxRelay state access from
net_processing.cpp and makes the guarded TxRelay data private without
changing intended relay behavior.

Document the caller serialization required across relay scheduling and
batch processing, provided by g_msgproc_mutex in SendMessages().
Make TxInventoryBatch move-only and hide its backing vector from
net_processing.cpp.

Expose semantic operations for batch state, queued candidate snapshots,
draining, clearing, and erasure. ReturnTxInventory() takes the batch
object itself. Candidate snapshots and drains return owned vectors
without exposing references to batch storage.
Add focused unit coverage for node::TxRelay's public behavior:
bloom-filter lifecycle, inventory gating before the first send schedule,
known-inventory deduplication, state accessors, BIP37 merkle block
creation, and the snapshot/return inventory-batch API (including
conservation across repeated drain rounds and under concurrent
PushInventory()).

These tests exercise TxRelay entirely through its public interface and
provide guardrails for the private-state and locking changes.
Add a fuzz target that exercises TxRelay's public operations in random
order: relay flag changes, bloom-filter updates, known transaction
inserts, send scheduling, inventory queueing, fee-filter state, and the
snapshot/return inventory-batch API.

Seed the test random context because CRollingBloomFilter uses global
random state. This keeps the target deterministic for a given fuzz
input.
Replace TxRelay's RecursiveMutex members with plain Mutex now that
callers no longer take those locks directly.

Annotate the bloom-filter mutex as acquired after the inventory mutex,
matching the only nested locking path in StartTxInventoryBatch().
Require callers of inventory-locking methods to hold neither mutex so
thread-safety analysis also rejects reversed lock order through helper
calls, while retaining the checks against recursive locking.
@w0xlt
w0xlt force-pushed the refactor/replace-txrelay-recursive-mutexes branch from e8dbc6e to 4ac05f0 Compare September 15, 2026 20:04
@w0xlt

w0xlt commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Rebased.

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.

8 participants