Skip to content

refactor: extract per-message helpers from ProcessMessage (move-only) - #35502

Open
w0xlt wants to merge 11 commits into
bitcoin:masterfrom
w0xlt:refactor/extract-processmessage-helpers
Open

w0xlt wants to merge 11 commits into
bitcoin:masterfrom
w0xlt:refactor/extract-processmessage-helpers

Conversation

@w0xlt

@w0xlt w0xlt commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

PeerManagerImpl::ProcessMessage() is a ~1500-line function handling every p2p message type inline, which makes it hard to navigate and review.

This PR continues splitting it into per-message helper functions, following the pattern of the recently merged fa5ab02 (ProcessPong()) and fa55723 (ProcessAddrs()), as suggested by maflcko #34588 (comment).

A preparatory commit removes the __func__ prefix from one getheaders debug log, so moving it doesn't change the output.

Nine handlers are extracted, one move-only commit each:

  • ProcessGetAddr() — getaddr
  • ProcessGetDataMessage() — getdata (named to avoid colliding with the existing ProcessGetData(), which services the request queue this handler fills)
  • ProcessGetBlocks() — getblocks
  • ProcessGetHeaders() — getheaders
  • ProcessInv() — inv
  • ProcessSendTxRcncl() — sendtxrcncl
  • ProcessTx() — tx
  • ProcessCompactBlock() — cmpctblock
  • ProcessVersion() — version

Each extraction commit is a code move with indentation adjustments: the only new lines are the declaration (with thread-safety annotations), the function signature, and the one-line call site.
Each call site is Helper(...); return;, so return statements inside the moved bodies keep identical semantics. No behavior change beyond debug log output.

One final cleanup commit normalizes the remaining formatting, replaces equivalent break statements with return in ProcessSendTxRcncl(), and simplifies the send_getaddr conditional in ProcessVersion().

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

Declarations and definitions are placed next to related existing helpers (e.g. ProcessGetDataMessage next to ProcessGetData, ProcessGetBlocks next to ProcessGetBlockData, ProcessGetAddr after ProcessAddrs).

@DrahtBot

DrahtBot commented Jun 10, 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 l0rinc, vasild, pablomartin4btc
Concept ACK stickies-v, theStack
Stale ACK pseudoramdom

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:

  • #36906 (Detect transaction problems early during deserialization by sipa)
  • #36787 (cmpctblock: Cache serialized cmpctblock msg for relay [part of prefill series] by davidgumberg)
  • #36607 (private broadcast: Extra guard against unintended non-private broadcast of private transactions by optout21)
  • #36477 (private broadcast: show finished transactions in getprivatebroadcastinfo by vasild)
  • #35936 (net: reject oversized locators before allocating by l0rinc)
  • #35920 (net_processing: Ignore MSG_WITNESS_TX entries from INV messages by ajtowns)
  • #35591 ([DO NOT MERGE] Erlay: bandwidth-efficient transaction relay protocol (Full implementation) by sr-gi)
  • #35558 (p2p: Prefill compact blocks by davidgumberg)
  • #35522 (refactor: Extract per-message helpers from SendMessages() (move-only) by pablomartin4btc)
  • #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.

@stickies-v

Copy link
Copy Markdown
Contributor

Concept ACK. Pretty straightforward change that makes it easier to navigate net_processing and better encapsulates logic.

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

Fwiw this has been proposed at least once: #9608 (it seems to have failed more due to lack of review back then rather than on strong pushback, as far as I understand)

@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'm in favour of these refactoring, while reviewing #34824 also identified another possible candidate SendMessages() which is in the same file.

@pseudoramdom

Copy link
Copy Markdown
Contributor

code review ACK 4fe745f
Except for a new comment for ProcessGetDataMessage, verified the change is a move-only refactor.
Also verified using git show--color-moved=dimmed-zebra --color-moved-ws=allow-indentation-change <commit> against each commit.

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

ProcessMessage() went from ~1500 to ~1000 lines, but CMPCTBLOCK (248 lines) and VERSION (235 lines) remain the two dominant inline blocks — extracting those two alone would drop it another ~480 lines, bringing it under 550. The same move-only pattern applied here would make both independently reviewable. Not a blocker, perhaps worth a follow-up PR in the same vein?

On a side note, on the previous attempt mentioned above, there were concerns about "obscuring the control flow", I don't think this is the case here.

@davidgumberg

Copy link
Copy Markdown
Contributor

Concept -0

Let's say I'm reading a function called ProcessBlock() in net_processing.cpp:

  • Is this function called by ProcessMessage()?
  • Does ProcessMessage() do any set up before invoking ProcessBlock()?
  • Are there any other callers of ProcessBlock() and what are their expectations?
  • Are all the callers of ProcessBlock() in the process messages thread?

These questions have to be answered when reading / modifying code and for all of the logic that lives in the ProcessMessage() ~switch statement these ambiguities don't exist. I think ProcessBlock() is a good example because it has multiple callers, and anyone reading it or modifying it should find them and think carefully about what they all do. That is a cost paid for by the reusability of ProcessBlock().

I think the main thing I don't share is the feeling that ProcessMessage() is too long. It's pretty flat, and there is ~0 state that lives outside of the if(msg_type) {, so I don't feel burdened by any of the rest of the function when I'm reading the logic for the message I'm interested in.

Not trying to bikeshed, the PR seems reasonable and everything would be fine if it was merged, just the POV of one person that happens to like ProcessMessage().

@w0xlt

w0xlt commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@davidgumberg Fair point. I agree the cost is real when a helper has multiple callers like ProcessBlock(), because setup and caller assumptions become less local.

These extractions are different though: they are private, single-caller helpers from ProcessMessage(), called as Helper(...); return;, so the control flow remains simple.

The benefit I see is lock reasoning. ProcessMessage() has to carry the broad lock contract needed by all branches:

EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_most_recent_block_mutex,
                         !m_headers_presync_mutex, g_msgproc_mutex,
                         !m_tx_download_mutex)

After extraction, each handler states only what it actually needs. For example, ProcessGetAddr() requires only g_msgproc_mutex, while ProcessTx() requires g_msgproc_mutex, !m_peer_mutex, !m_tx_download_mutex.

So this does not add runtime safety by itself, but it makes the per-message lock contract more local and compiler-checked.

Besides that, ProcessMessage() arguably accumulates disproportionate responsibility, and this extraction pattern addresses that, though I agree this is a more subjective point.

@maflcko

maflcko commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Let's say I'm reading a function called ProcessBlock() in net_processing.cpp:

* Is this function called by `ProcessMessage()`?

Should be easy to answer with 'yes', otherwise the function wouldn't sit in the peer manager impl?

* Does `ProcessMessage()` do any set up before invoking `ProcessBlock()`?

Edit: I'd say generally the goal should be to avoid setup, but here it should be obvious from the function signature, which is passed min_pow_checked (and other stuff). There is also the possibility of different message types doing different setup steps, one would have to read the handshake code either way, before and after this pull request.

* Are there any other callers of `ProcessBlock()` and what are their expectations?

Should be easy to answer by looking at the header: If the function is public in the header, it is called externally. If it is not in the header, then it is not called externally. Generally, I don't think any Process* handler was ever exposed in the header?

* Are all the callers of `ProcessBlock()` in the process messages thread?

Should be easy to answer with yes, because no process handler was ever exposed publicly. Also, it should be easy to verify with a single call to git grep.


Generally, I think the benefits here are limited, because devs generally know that at most a single message is handled in the large body (and thus no variables leak from one message handling block to the next). However, I think there is still a benefit in being able to review code changes with the git option git diff --function-context easier.

Previously, it would basically print the whole file, even if only a single line in a single message type handling was changed. At least for me this makes review harder because I have to scroll past the irrelevant white lines every time and risk missing a green or red line.

After this change, git diff --function-context nicely prints only the relevant context, so at least for me review would be easier. Also, parts of this file already use this pattern, so for consistency it also makes sense. So I am Concept +1, but this is just me, and maybe other people are using a different review flow?


@w0xlt Please don't @ in pull descriptions. If this pull was merged, it would lead to ping spam every time the merge is cherry-picked.

@davidgumberg

davidgumberg commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Let's say I'm reading a function called ProcessBlock() in net_processing.cpp:

  • Is this function called by ProcessMessage()?

Should be easy to answer with 'yes', otherwise the function wouldn't sit in the peer manager impl?

I meant directly, this is basically the same point as the set-up one.

  • Does ProcessMessage() do any set up before invoking ProcessBlock()?

Edit: I'd say generally the goal should be to avoid setup, but here it should be obvious from the function signature, which is passed min_pow_checked (and other stuff). There is also the possibility of different message types doing different setup steps, one would have to read the handshake code either way, before and after this pull request.

Right, but after this PR you have to look in multiple places, even if there is only one caller that doesn't do any setup and it's ProcessMessage()

  • Are there any other callers of ProcessBlock() and what are their expectations?

Should be easy to answer by looking at the header: If the function is public in the header, it is called externally. If it is not in the header, then it is not called externally. Generally, I don't think any Process* handler was ever exposed in the header?

  • Are all the callers of ProcessBlock() in the process messages thread?

Should be easy to answer with yes, because no process handler was ever exposed publicly. Also, it should be easy to verify with a single call to git grep.

Yes, all of these questions can be answered quite easily by checking in one or two files and doing a grep or two, my point is that one doesn't have to just check the header and do an extra grep or two now.

e.g. I don't use git diff --function-context but it sounds like reviewing ProcessMessage() might be pretty annoying if one does that. Of course I could recommend that you use a different set of flags or a different tool, or just open another window with the function in it, but any of these "solutions" would add friction for you i.e. they suck in comparison to using the tool / workflow you already like and are used to.

That being said, it sounds like other contributors prefer the style of this PR to the style of master, and given that this is a stylistic question the thing that people prefer is definitely the thing that should happen.

@l0rinc

l0rinc commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

rereACK 0e3c1a2

I checked each commit manually (inlined the content back and checked the diff). The extractions are clean code moves, with a minimal log cleanup in the first commit and formatting and equivalent control-flow cleanups in the last.

@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 0e3c1a2

Thanks for taking the suggestion dropping __func__ from debug log (in prepare commit).

Please rebase due to #36752.

@vasild vasild 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 0e3c1a2 (modulo the conflict with #36752)

Long overdue, thank you!

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK 0e3c1a2de03596cfaf5de25cc052b96ef88728af (modulo the conflict with https://github.com/bitcoin/bitcoin/pull/36752)

Long overdue, thank you!
-----BEGIN PGP SIGNATURE-----

iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmrzI6obFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/ceQf/37r2DIZSTmzPhgHtvpw
ZmrfCLgPlHYdT+8NbB+TBejOCX2JDqpvB9gAhDhZgt+mLEwQNMvnjijzsLifiVDw
JDpK6Kffm5dSJcmZYe+pmM7901mQngXALoe03nEnjiQkgW0TbA8LdmfJEDFVX8Sz
pVdxGYyQCsn4uh8xfmFu8FbQ5/UlEwmsF087RZsalseYkRPORtzCZaHnSuGE7zLp
UmgWRQX0l1DLcmZtZw74OZRWWBfgnwBvv8FESp4L+g6aGbxLE2dMSeaIfz99yo+n
VUM/AzvMd2mbSc/Q+E8/+UNkSYJoAtsihjyk/7fW1BujlQ7dapM0S+4eNgeeqNEM
cnAoD25QhHwgeeumGVnLxSCW95K6QDksDEmNYYKeA6vPUzQOSfgkHYY0EKSsH7fH
eGg/vCEZBr6kel46dlsCCnRM/EMwOio+u2Gg9W19s4HBd/crLi0uhAZD5TFhkWiJ
wau49RVhW/OmxF0pxxlKMlqhXouBM5mL1Rtn6ZfIKQxMGfHScKdPZ5UBY7YCvXBL
sQ9LXVJwWaS6fca956j7ypc0KErKtUckUBWFDIt2yWgMt92InFCl0GSDiSwvXMAv
X5SroFtsMu8IyQ1P4OW5N6PUq419QWt6T65H3pgSEl9FbvFLiMo4NbnGXJedH9rk
9aYFVWirMpQS6lXXrHwSnECmVSFU8lKwPh4ZW7TbgSNqI2kQvv5EA9OgbXZrZD4h
Htpm71ktSftD744l0bAJqKU4zub+vQBJIuT/C33x6OaSXAgVSFhXouLD4JdRK+r9
3UMOQ5ytBLEETAelTmkJkBTFkCfkgtGfngf4eiIJYR0sCcLffHV1bhC/kLYvrRy6
/D7QApBv7/vO14G5bYKTetqmLo9fKSrtFhuORk9MK8FEOjjGkmYWO98yh1VIprEt
aFCGXI0mJGnmdKFNNpzNMr6o1GSKM2NN72OTLFduOCtDaKMKxgUpZo21bVjoJ3fZ
HlWE0bvjbzFachuDZoi0ARE/ehHeBdlXN1NhqOuEBKc2Rx0pl9+3YFjygApr9uff
wq+acCeWScahGNKgq6lJ2uKxWwZyknNpkug/uNEsIaaZJIZpHCDbnSzMuhPiwua+
ity/v38OWb7WSyFjpc/5dF/GKxJ9KEbL4Z2KXGmd0ztTmATGGaq41JT7I9Rce5Ad
PS/2pRQGbFLJf0PpW4yIhSY00b7CFqvf58bc4hbqb1K+1CvFBNSCGuIRszTeHm4z
dxQZQSX0WmnCkiDYEpznRplIhDcFK6UdvaM/stz1KHJNrrHZHk/8O3CTMF5q2Pvr
GWriLYDZYgkJ0jqWHvPhwqPbqBhjdu6kkfPK5bbQaI5Qijn4a0k2DB897wEXd/mC
j8Y=
=FF1a
-----END PGP SIGNATURE-----

vasild's public key is on openpgp.org

w0xlt and others added 11 commits November 11, 2026 10:41
The debug log for ignored old block header requests prefixes its
message with __func__. The logging macros already record the calling
function, which -logsourcelocations prints, so the prefix adds nothing.

It also ties the log text to the name of the enclosing function, so
moving the getheaders handling into its own helper would change it.
This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space

Co-authored-by: Lőrinc <[email protected]>
This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space
This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space

Co-authored-by: pablomartin4btc <[email protected]>
Co-authored-by: Lőrinc <[email protected]>
This commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space

Co-authored-by: pablomartin4btc <[email protected]>
Normalize brace placement, pointer and reference spacing, blank lines,
and single-statement conditionals in the extracted handlers.

Use returns in ProcessSendTxRcncl() and remove the send_getaddr temporary
in ProcessVersion(), preserving the existing control flow.

Co-authored-by: Lőrinc <[email protected]>
@w0xlt
w0xlt force-pushed the refactor/extract-processmessage-helpers branch from 0e3c1a2 to e7120dc Compare November 11, 2026 18:48
@l0rinc

l0rinc commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

reACK e7120dc

Only the ProcessSendTxRcncl() extraction changed in the rebase after #36752.
Small description nits: line count and "no behavior change" need some minor edits.

@sedited, could we prioritize these moves to spare the author repeated rebases?

@w0xlt

w0xlt commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@l0rinc Thanks for the re-review. Both are fixed in the description: the line count is now ~1500, and the "no behavior change" sentence now mentions the debug log differences.

@maflcko

maflcko commented Nov 12, 2026

Copy link
Copy Markdown
Member

This conflicts with a reviewed pull that is marked for possible backport. I think it is a better use of review resources to defer this pull and rebase/review it later than to make the backport differ, which would require additional review/"rebase".

@w0xlt

w0xlt commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

Makes sense, thanks @maflcko.
For tracking: I assume this is 36521?

@vasild vasild 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 e7120dc

This conflicts with a reviewed pull that is marked for possible backport

Which one?

For tracking: I assume this is 36521?

#36521 is closed and not for backport?

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK e7120dc7002fd91c061df45e58d527fb03dd16e3

> This conflicts with a reviewed pull that is marked for possible backport

Which one?

> For tracking: I assume this is 36521?

https://github.com/bitcoin/bitcoin/pull/36521 is clos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tqco/v/lcGOREEpESL+xT1pLurPnyoGRo0wuKFK1Qpk2WR
PI7TTN5dZfEhSH4JgmLJLrn/S2BZMxLURGVcrcQWzBe/ORHE65aenTPS6sHTa3nM
xM8vN4rUNL39bmZuQxcJUOrFpX3PfriKj8pzKP7aHh1W8KHdtppPBTOKlReVCG0n
LA1LKUBvcx4+sX2GJh+iAIFQFCq6DJ5bLNeXsqUSWMFN//E+FZ0cJzKxqAfMDxwl
IDs/GAmTczQpyTIyrVAFDTAEjDVujXHTh4UrgLizH6wvl7Cnv/Tca1R43iRao2iD
FrQSVtTlMKJeKR8dSXOBViGGWgjmv1YbXJ9mc32kP7rko7h3TlSSzQAITN7H9xEQ
j0oWqO2IgVGbHs6lvzoZSkEuibbKJu7IwQe/X2dEHOwzX7CU3nGDw6cSPfbSkqwn
wxw=
=gy8S
-----END PGP SIGNATURE-----

vasild's public key is on openpgp.org

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

Clean rebase: range-diff vs 0e3c1a2 only touches the ProcessSendTxRcncl() extraction, picking up the reordering from #36752 (disconnect after VERACK before the m_txreconciliation check), still move-only.

#36521 is closed and not for backport?

Adding to @vasild's point: #36521 was closed and split up. The part marked for backport now, #36895 (33.0 milestone), doesn't touch net_processing.cpp and no longer conflicts with this PR. The other split-off, #36906, only has a trivial one-line conflict (TX_WITH_WITNESS -> TX_WITH_WITNESS_P2P in the tx handler) and isn't marked for backport.

@vasild, if you have some time, I'd really appreciate your review on #35522 (the same kind of extraction/ refactoring for SendMessages()), which I put in draft for the same reason @maflcko raised here. It doesn't conflict with #36895 or #36906 either, so I'll undraft it once I rebase it.

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.

10 participants