mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:50:37 +00:00
refactor: extract per-message helpers from ProcessMessage (move-only) #35502
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35502
Loading…
Reference in a new issue
No description provided.
Delete branch "refactor/extract-processmessage-helpers"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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
fa5ab0220e(ProcessPong()) andfa55723b8f(ProcessAddrs()), as suggested by maflcko https://github.com/bitcoin/bitcoin/pull/34588#issuecomment-4658892004.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()—getaddrProcessGetDataMessage()—getdata(named to avoid colliding with the existingProcessGetData(), which services the request queue this handler fills)ProcessGetBlocks()—getblocksProcessGetHeaders()—getheadersProcessInv()—invProcessSendTxRcncl()—sendtxrcnclProcessTx()—txProcessCompactBlock()—cmpctblockProcessVersion()—versionEach 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;, soreturnstatements inside the moved bodies keep identical semantics. No behavior change beyond debug log output.One final cleanup commit normalizes the remaining formatting, replaces equivalent
breakstatements withreturninProcessSendTxRcncl(), and simplifies thesend_getaddrconditional inProcessVersion().Each extraction commit can be reviewed with the git options:
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-spaceDeclarations and definitions are placed next to related existing helpers (e.g.
ProcessGetDataMessagenext toProcessGetData,ProcessGetBlocksnext toProcessGetBlockData,ProcessGetAddrafterProcessAddrs).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.
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:
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.
Concept ACK. Pretty straightforward change that makes it easier to navigate net_processing and better encapsulates logic.
Concept ACK
Fwiw this has been proposed at least once: https://github.com/bitcoin/bitcoin/pull/9608 (it seems to have failed more due to lack of review back then rather than on strong pushback, as far as I understand)
Concept ACK.
I'm in favour of these refactoring, while reviewing #34824 also identified another possible candidate
SendMessages()which is in the same file.code review ACK 4fe745f27bd8a4a637df522421a4a7104923ca3e
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.code review ACK 4fe745f
Verified each commit is a pure code move (only new lines are declarations, call sites, and one doc comment), call sites preserve return semantics, and the thread-safety annotations match what each body locks. It compiles cleanly with clang -Wthread-safety.
ACK
github.com/bitcoin/bitcoin@4fe745f27b.ProcessMessage()went from ~1500 to ~1000 lines, butCMPCTBLOCK(248 lines) andVERSION(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.
Concept -0
Let's say I'm reading a function called
ProcessBlock()innet_processing.cpp:ProcessMessage()?ProcessMessage()do any set up before invokingProcessBlock()?ProcessBlock()and what are their expectations?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 thinkProcessBlock()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 ofProcessBlock().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 theif(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().@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 asHelper(...); 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:After extraction, each handler states only what it actually needs. For example,
ProcessGetAddr()requires onlyg_msgproc_mutex, whileProcessTx()requiresg_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.Should be easy to answer with 'yes', otherwise the function wouldn't sit in the peer manager impl?
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.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?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-contexteasier.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-contextnicely 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.I meant directly, this is basically the same point as the set-up one.
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()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-contextbut it sounds like reviewingProcessMessage()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.
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased.
All suggestions addressed.
🐙 This pull request conflicts with the target branch and needs rebase.
tested ACK
ace762905fRebased and reimplemented the extractions, and generated missing test coverage locally to test that the before/after behavior doesn't change. I also compared the implementation with this series and reviewed each commit using
--color-moved=dimmed-zebra --color-moved-ws=ignore-all-space.The change looks good to me. Thanks for this cleanup.
My inline suggestions are nonblocking, but since the extractions are straightforward, I think one or two cleanup and formatting commits after the move-only series would be reasonable.
The PR description also needs some updates: it still states "Seven handlers" although there are nine, omits
ProcessCompactBlock()andProcessVersion()from the list, and has a double comma afterProcessAddrs().Seems to me this is basically just:
nit: this log changed because of
__func__returning "ProcessGetHeaders" intead of "ProcessMessage" - which is probably fine, give it's a debug log, but might be worth a mentionnit: in a separate commit consider reformatting these, we shouldn't add new code that's off from the start
indentation is weird here, in a cleanup commit at the end we should normalize these
Note: these trailing
returnsallow us to cleanly extract the helpers since the previousreturnvalues short-circuited the whole external method - while after extraction they only cut the extracted method short.Can be
returnafter the move for consistency, it's confusing to have bothbreakandreturn(doing the same in this context)Thanks. Done.
Thanks. Done.
Thanks. Done.
Thanks. Done.
Thanks. Done.
Thanks. Done.
retested ACK
cf0c89d6dcThis remains a straightforward refactor.
Since my last ACK, the changes are mostly minimal reformatting and the equivalent
break→returnandsend_getaddrcleanups as suggested.ACK
cf0c89d6dcThanks for taking my suggestion to also extract
ProcessCompactBlock()andProcessVersion().Also, since my last review, feedback from @l0rinc has been addressed and a new cleanup commit has been added.
Earlier concerns remain unresolved; see the Run archive linked from the Review report.
No verified findings are available from this review.
Review coverage was incomplete.
Reviewed:
e7120dc7002f· Review report · Previous reportspermalink
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased
re-ACK
87ca532651Confirmed pure rebase since my last review.
8 of 10 commits are byte-identical; the other 2 (
ProcessTx(),ProcessVersion()) differ only in incidental context lines absorbed from unrelated upstream changes (private-broadcast internals, a ping-timeout-related doc comment) — nothing intentional added or removed.nit: as @maflcko suggested in https://github.com/bitcoin/bitcoin/pull/35522#issuecomment-6144362450, we shouldn't be using
__func__in the logs. I've checked that the logging macros already capture the calling function viaSourceLocation, which is available on demand with-logsourcelocations(e.g., tests enable it unconditionally — seesetup_common.cppandtest_node.py). Perhaps you can add a prepare commit that removes the prefix from the debug logs used inProcessMessage().🐙 This pull request conflicts with the target branch and needs rebase.
Thanks, done in
4f7f24d813as a prepare commit, so the ProcessGetHeaders() move is now move-only.Rebased.
rereACK
0e3c1a2de0I 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.
🐙 This pull request conflicts with the target branch and needs rebase.
re-ACK
0e3c1a2de0Thanks for taking the suggestion dropping
__func__from debug log (in prepare commit).Please rebase due to #36752.
ACK
0e3c1a2de0(modulo the conflict with https://github.com/bitcoin/bitcoin/pull/36752)Long overdue, thank you!
Show Signature
vasild's public key is on openpgp.org
reACK
e7120dc700Only 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?
@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.
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".
Makes sense, thanks @maflcko.
For tracking: I assume this is 36521?
ACK
e7120dc700Which one?
https://github.com/bitcoin/bitcoin/pull/36521 is closed and not for backport?
Show Signature
vasild's public key is on openpgp.org
re-ACK
e7120dc700Clean rebase: range-diff vs
0e3c1a2de0only touches theProcessSendTxRcncl()extraction, picking up the reordering from #36752 (disconnect afterVERACKbefore them_txreconciliationcheck), still move-only.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.cppand no longer conflicts with this PR. The other split-off, #36906, only has a trivial one-line conflict (TX_WITH_WITNESS->TX_WITH_WITNESS_P2Pin thetxhandler) 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.