Skip to content

refactor: Extract per-message helpers from SendMessages() (move-only) - #35522

Open
pablomartin4btc wants to merge 19 commits into
bitcoin:masterfrom
pablomartin4btc:refactor/extract-sendmessages-helpers
Open

pablomartin4btc wants to merge 19 commits into
bitcoin:masterfrom
pablomartin4btc:refactor/extract-sendmessages-helpers

Conversation

@pablomartin4btc

@pablomartin4btc pablomartin4btc commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

PeerManagerImpl::SendMessages() is a ~500-line function handling every p2p conditional send message type inline, which makes it hard to navigate and review. This was reduced to less than 90 lines.

I've identified this issue/ possible improvement while reviewing #34824.

-Notes:

First (prepare) commit removes the unnecessary __func__ prefix from the debug logs in SendMessages(), as suggested by maflcko. The logging macros already capture the calling function via SourceLocation, available on demand with -logsourcelocations.

Each of the following 17 commits represents a helper function extraction so it can be easily reviewed, it's only a pure code move, the only new lines are the declaration (with thread-safety annotations), the function signature, and the one-line call site, and they can be reviewed with the git options: --color-moved=dimmed-zebra --color-moved-ws=ignore-all-space.

One final cleanup commit normalises formatting and simplifies some of the extracted helpers, preserving existing control flow and lock scopes.

@DrahtBot

DrahtBot commented Jun 12, 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 w0xlt
Concept ACK hodlinator

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:

  • #36955 (p2p: Use separate compact block nonce per network by mzumsande)
  • #36787 (cmpctblock: Cache serialized cmpctblock msg for relay [part of prefill series] by davidgumberg)
  • #35591 ([DO NOT MERGE] Erlay: bandwidth-efficient transaction relay protocol (Full implementation) by sr-gi)
  • #35558 (p2p: Prefill compact blocks by davidgumberg)
  • #35502 (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)
  • #35229 (refactor: Use CBlockIndex parameters as reference by optout21)
  • #34824 (net: encapsulate TxRelay state and replace recursive mutexes 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.

@pablomartin4btc

Copy link
Copy Markdown
Member Author

@w0xlt, my first impulse is to put it into draft till your both PRs #34824 and #35502 land and get merged before but perhaps you find this useful and easier to work on those changes on top of this one?

@w0xlt w0xlt 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, same pattern as #35502.

Comment thread src/net_processing.cpp Resolved
@w0xlt

w0xlt commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

@w0xlt, my first impulse is to put it into draft till your both PRs #34824 and #35502 land and get merged before but perhaps you find this useful and easier to work on those changes on top of this one?

I don’t think this PR needs to be draft. Keeping it open is useful for review.

If this, #34824, or #35502 lands first, rebasing should be straightforward.

@pablomartin4btc

Copy link
Copy Markdown
Member Author

-Updates:

  • Corrected misleading comment on MaybeSendTxMessages(), observed by @w0xlt.

(iwyu CI failure is not related and I think it's being fixed in #35535)

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/27553084448/job/81447465260
LLM reason (✨ experimental): CI failed because IWYU detected and auto-modified an include in src/bench/pool.cpp (and intentionally returned failure: “Failure generated from IWYU”).

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.

@pablomartin4btc

Copy link
Copy Markdown
Member Author

-Updates:

  • Rebased.

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

Was recently reviewing some code here and felt it would have been nice to be able to refer to smaller parts of SendMessages() by name.

@pablomartin4btc
pablomartin4btc marked this pull request as draft November 12, 2026 22:37
@pablomartin4btc

Copy link
Copy Markdown
Member Author

Converting to draft. I'll rebase once #36521 gets in.

pablomartin4btc and others added 19 commits November 24, 2026 17:20
These four debug logs in SendMessages() use __func__ to prefix their
output. The logging macros already capture the calling function, file,
and line automatically via SourceLocation, available on demand with
-logsourcelocations, so the manual __func__ prefix is redundant.

It is also fragile under refactoring: relying on __func__ for a log
line's identity means moving that log into a differently-named helper
silently changes the printed output, even though nothing about what is
being logged changed. Writing each line so it reads clearly without
needing the surrounding function's name avoids that.

No other change.
Extracts the periodic relay scheduling logic from the tx-relay section
of SendMessages() into a self-contained helper. The helper determines
whether it is time to trickle inventory to a peer and clears the
pending inventory set if the peer has requested no transaction relay.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the BIP35 mempool-response block from the tx-relay section of
SendMessages() into a self-contained helper. The m_send_mempool guard
moves inside as an early return, keeping the call site a single line.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the regular tx-inventory relay selection block from the
tx-relay section of SendMessages() into a self-contained helper.
The helper covers candidate collection, heap-based fee/topology
sorting, bloom/feerate filtering, and the m_last_inv_sequence update.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the initial headers-sync kick-off block from SendMessages()
into a self-contained helper. The helper handles the fSyncStarted
guard, the single-peer-or-close-to-tip condition, the getheaders
locator construction, and the timeout initialisation.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the block-announcement section from SendMessages() into a
self-contained helper. The helper covers header-relay candidate
selection, compact-block sending (with cached-message optimisation),
multi-header relay, and the inv fallback path.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the block-inv drain loop from SendMessages() into a
self-contained helper. The helper flushes m_blocks_for_inv_relay
into the caller-provided vInv vector so downstream tx-relay
logic can continue appending to the same batch.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the stall/timeout checks from SendMessages() into a
self-contained helper: block-download stall detection (with adaptive
timeout backoff), per-block in-flight timeout, ping timeout, and
headers-sync timeout. Returns true when the caller should return
early, preserving identical semantics, including the manual-peer
block-download cooldown.

The ping timeout check was added to SendMessages() upstream after this
branch's original base; it's included here as part of the same move,
taking the now parameter needed for it.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the getdata section from SendMessages() into a self-contained
helper. The helper covers block requests (FindNextBlocksToDownload and
historical-block ranges), transaction download requests, and the final
getdata flush. vGetData is local to the helper; the m_tx_download_mutex
acquisition moves inside.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the compact-block/headers send path from
MaybeSendBlockAnnouncements() into a self-contained helper. The helper
chooses between a compact-block (with cached-message optimisation),
a headers message, or sets fRevertToInv when neither format applies.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the inv-fallback path from MaybeSendBlockAnnouncements() into
a self-contained helper. The helper inv-announces the chain tip when
neither a headers nor a compact-block relay was possible.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the stall-detection block from CheckBlockSyncTimeouts() into a
self-contained helper. The helper detects when the block-download window
has stalled, pauses block requests to manual peers, and disconnects other
peers. It applies adaptive timeout backoff when local bandwidth may be
insufficient.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the per-block in-flight timeout check from CheckBlockSyncTimeouts()
into a self-contained helper. The helper disconnects a peer when a requested
block has been in flight longer than the threshold, compensating for the
number of peers with validated downloads.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space

Co-authored-by: w0xlt <[email protected]>
Extracts the initial headers-sync timeout check from CheckBlockSyncTimeouts()
into a self-contained helper. The helper disconnects (or resets sync state for
NoBan peers) when initial headers sync has stalled, and resets the timeout
once the chain has caught up.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space

Co-authored-by: w0xlt <[email protected]>
Extracts the block getdata request queuing logic from MaybeSendGetData() into
a self-contained helper. The helper queues blocks via FindNextBlocksToDownload
and TryDownloadingHistoricalBlocks, and marks a stalling peer when the
in-flight queue runs empty.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the transaction getdata request queuing logic from MaybeSendGetData()
into a self-contained helper. The helper acquires m_tx_download_mutex, iterates
pending tx requests from m_txdownloadman, and flushes intermediate batches when
the getdata size limit is reached.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space

Co-authored-by: w0xlt <[email protected]>
Extracts the sync-peer eligibility computation from the SendMessages() cs_main
block into a self-contained helper. The helper initialises m_best_header if
needed and returns whether blocks and headers should be synced from this peer
based on preferred-download status and current in-flight state.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
Extracts the tx-relay trickle and inventory dispatch block from the
SendMessages() cs_main block into a self-contained helper. The helper acquires
the per-peer tx_inventory_mutex, schedules the trickle interval, and
conditionally sends the mempool response and tx inventory.

This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space

Co-authored-by: w0xlt <[email protected]>
Rename MaybeSendInitialGetheaders() to MaybeSendInitialGetHeaders() to
match MaybeSendGetHeaders(), and normalize pointer/reference spacing and
single-statement conditionals.

Share the transaction relay scheduling guard, combine the bloom-filter
and staller checks, use empty() for container checks, and simplify the
timeout and sync-selection returns. Preserve evaluation order and lock
scopes.

Co-authored-by: w0xlt <[email protected]>
@pablomartin4btc
pablomartin4btc force-pushed the refactor/extract-sendmessages-helpers branch from 4d707f6 to 53e896e Compare November 24, 2026 20:35
@pablomartin4btc
pablomartin4btc marked this pull request as ready for review November 24, 2026 21:02
@pablomartin4btc

Copy link
Copy Markdown
Member Author

-Updates:

  • Rebased.

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

reACK 53e896e

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants