mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:44:38 +00:00
refactor: Use CBlockIndex parameters as reference #35229
No reviewers
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!35229
Loading…
Reference in a new issue
No description provided.
Delete branch "2605-block-param-ref"
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?
This is a janitorial refactor, a continuation of #34440. Input method parameters of type
const CBlockIndex*are changed to referenceconst CBlockIndex&in some places where it makes no sense to call with a nullptr.Motivation: slight improvement in code quality, maintainability and robustness.
The following methods are affected:
LastCommonAncestor()in chain.hPeerManagerImpl::FindNextBlocks()(net_processing.cpp)PeerManagerImpl::TryDownloadingHistoricalBlocks()(net_processing.cpp)BlockFilterIndex::LookupFilterRange(),BlockFilterIndex::LookupFilterHashRange()(blockfilterindex.h), andLookupRange()in blockfilterindex.cppBaseIndex::ProcessBlock()(base.h)General guidelines:
const CBlockIndex*, and by contract it cannot be nullptr, change it toconst CBlockIndex&. The reference type is an implicit documentation of the nun-nullptr invariant.reserve()std::setwould result in some copy constructor callsstd::optionalcannot hold a reference typeThe 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:
src/and treat them as errors by hebasto)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 typos and grammar issues:
src/net_processing.cpp:Block are placed into block_indexes.→Blocks are placed into block_indexes.[subject–verb agreement]2026-11-27 12:52:18
Concept ACK
nit: developer notes prefer camel_case while you're touching this
Concept ACK.
Refactor makes sense to me. Changing parameters from const
CBlockIndex*toconst CBlockIndex&wherenullptris not a valid state improves clarity and gives stronger compile-time guarantees around non-nullability by making the invariant explicit.Nit: We can make this comment a bit more concise and technically precise.
Right now it mentions
reserve, but the ultimate underlying constraint is simply thatstd::vectorfundamentally cannot hold references entirely. We can strip out the mention of the specific method and focus purely on the core safety invariant and the language rule.I think we can explicitly pass the default
nullptrwith an inline comment here to match the codebase convention.As explained previously, this seems confusing, see https://github.com/bitcoin/bitcoin/pull/34440#discussion_r3085393412
If the code-typing overhead of
.get()is not too much, why not just use std::reference_wrapper, which enforces everything at compile-time without any runtime overhead and does not rely on a code comment?Did changes, following recent reviews. Thanks for the reviews!
What's changed:
PeerManagerImpl::FindNextBlocks(), for thevToFetchvector, usestd::reference_wrapper<const CBlockIndex>instead of pointers (new commit!)git range-diff dfe62214070408e699067598309b779c1ed1214d...ed44574efd38d4b7815ab96ae6f68f8b02dee88aIndeed, thanks for the reminder! I wanted to have here something to "code-show" the return-is-not-nullptr assumption. I've double-checked the usages (call sites), and this can't happen -- all chain segments must have the same genesis. Therefore I've changed it to
Assert. Similarly changed one other introducedAssumetoAssertinnet_processing.cpp.@musaHaruna , @maflcko : I was incorrect here, what I meant is that if
reference_wrapper's are used, thenresize()has a problem (notreserve()!), because it would call the default constructor, andCBlockIndexdoes not have one. But I realized now that this can be solved (by passing an instance to resize).So what I did:
reference_wrapperlocally inPeerManagerImpl::FindNextBlocks(). I think theget()is not a big inconvenience, and the zero memory and runtime overhead is important. In there the resize sets them all to a(*nullptr)initially, which kind of defies the purpose, but at least the intent is clear. I put this in a separate commit.I may reconsider keeping the
reference_wrappercommit or not, pending review.I will also consider using
reference_wrapperin theCChainclass member vector, which is a riskier change.This is not related to this PR, plus I don't see why to explicitly pass an optional parameters, so not taking this.
Done.
🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/26158964766/job/76945600531LLM reason (✨ experimental): CI failed due to a compiler error from Clang
-Werror: null pointer dereference to a reference innet_processing.cpp(line 1485).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.
Pushed compile fix: initializing the
reference_wrapperwithstd::ref(*(CBlockIndex*)nullptr)gave a build error on MacOS (but not locally). Now it's filled with theindex_walkinput parameter as a placeholder.Performed changes:
reference_wrapper's insidePeerManagerImpl::FindNextBlocks(). That's an internal, local usage, so there is not much benefit of this change there, hence I reverted it.CChain::vChainarray to storestd::reference_wrapper<CBlockIndex>items instead of pointers (new commit). This is to better show and ensure that entries are never null. The interfaces returning pointers are not changed.git range-diff 82fdd038cfe379c0dbdfda37e3504f97f8e21564...a1ed86a7e66c4f13dc58fab71982eba3340602e0There was an unrelated CI failure, but on the second try all CI builds passed.
The failure was in "Windows, ucrt, test cross-built":
seemingly an intermittent infrastructure issue, most likely unrelated to this PR.
https://github.com/bitcoin/bitcoin/actions/runs/26446276736/job/77856772060?pr=35229
Concept ACK
Pinging concept ackers @musaHaruna @stickies-v @w0xlt for another review.
Review failed because required verification did not complete.
Earlier concerns neither republished nor resolved: 1 minor finding · 2 suggestions. See the Run archive linked from the Review report for their assessments.
Review coverage was incomplete.
Reviewed:
bad93f723486· Review report · Previous reportspermalink
Reviewed the reference conversions, their call sites, and the relevant non-null and ancestry assumptions. I think the code looks good.
A couple of small suggestions:
chain.h, Could we include<functional>directly forstd::reference_wrapper, as recommended by the developers note?Could we use
std::ref(block)directly as theresize()fill value instead of constructing a localCBlockIndex placeholder? This would simplify the implementation by avoiding an unnecessary temporary object while preserving the behaviour for valid ancestry.Thanks for the review, @musaHaruna! Applied your suggestions.
git range-diff a1ed86a7e66c4f13dc58fab71982eba3340602e0...1b5108638b15aaa890657fe6d6d59e38e341b6f5Additionally, applied some minor changes (self-review):
git range-diff 1b5108638b15aaa890657fe6d6d59e38e341b6f5...8f3a7096b44aa2203ecdad6800d8c498c87b7d1cAlso rebased it.
(
git range-diff 8f3a7096b44aa2203ecdad6800d8c498c87b7d1c...61566b5a3a20e8b8f68d7cd1640b755131e9bd82)Done.
These parameters should be annotated with
LIFETIMEBOUNDWould it make sense to rename this to
m_chainif we are touching it here?Why not rename
vBlockshere toblock_indexes?Why not rename all these to modern snake_case from hungarianCamelCase? Since we're touching it?
Applied suggestions from @andrewtoth, thanks! (
LIFETIMEBOUND, renames).git range-diff 61566b5a3a20e8b8f68d7cd1640b755131e9bd82...f3a095ad3c8cc4ac319d37e233df2fb5285d0902Done
It makes sense, as its type is changed, most of its occurrences are touched. Done.
Done as a small housekeeping task (same commit, added co-author).
I like it, though it's a bit larger, unrelated change. I've done it in a new commit (the last commit, with co-author).
nit: PeerHasHeader() of net_processing.cpp might benefit from a change too:
pindex is always 'asserted' before calls of this method, except for when the method is given index->pprev in the same source file. So either index->pprev can be nullptr, and inside the method there should be an assert on the CBlockIndex pointer before dereferencing it, or we know that pprev cannot be null (or we assert it before the call), and that method could take a reference
ACK
f3a095ad3cIn commit
d41e5ffd98:nit: seems unrelated this (
d41e5ffd98) commit? And it's also not entirely correct at this point, entries can be nullptr duringSetTip's resize.nit: might
m_entriesorm_indexesbe a better name?nit:
std::vectoroffers more idiomatic methods here, while you're touching this:git diff on
f3a095ad3cThis sounds like a precondition on the parameter, but I think you meant to say that only non-null entries are appended?
nit: The index walking is an implementation detail and should not leak into the fn signature imo. I also interpret the docstring as
index_walkto be included inblocks, but I don't think that's the case. Suggest improving the docstring and renaming the parameter to e.g.after_block?In commit
f3a095ad3c:This commit feels pretty low-value to me. It's fine to modernize names as we touch them, or if names are not good, but not sure that applies here. If you prefer doing it in this PR regardless, I think we should use helpful names like
max_block_countandmax_heightinstead ofcountandwindow_end.Applied several smaller changes, following review from @stickies-v -- thanks!
The last, adjacent rename commit has grown. I've decided to keep it for now, but if there are doubts about its place here, or further suggestions to fix "one more thing", I will drop it.
git range-diff f3a095a...bad93f7This is meant to explicitly document an implicit, pre-existing assumption. This assumption makes it easier to switch to references.
You are right that commit-wise this is not the ideal spot. I've moved it to the "doc" commit.
Taken.
Good point, taken
Indeed, I was wrong here.
Done
Starting doing adjacent cosmetic changes is a slippery slope. I did a mechanical casing-only change to the non-touched parameters (in response to a review comment). But your point is also valid. I've decided to change the mentioned parameter names to more descriptive ones. This is the last such change; I will simply drop this commit if other review commits suggest that or suggest further improvements.