Skip to content

Add nullptr-check to CChain::Contains(), tests - #34416

Closed
optout21 wants to merge 2 commits into
bitcoin:masterfrom
optout21:cchain-contains
Closed

optout21 wants to merge 2 commits into
bitcoin:masterfrom
optout21:cchain-contains

Conversation

@optout21

@optout21 optout21 commented Jan 27, 2026 •

Copy link
Copy Markdown
Contributor

Add unit tests to the CChain class, and add a nullptr-check to CChain::Contains() to avoid potential memory access violation by nullptr dereference.

The CChain::Contains() method (in src/chain.h) dereferences its input without checking. The Next() method also calls into this with a nullptr if invoked with nullptr. While most call sites have indirect guarantee that the input is not nullptr, it's not easy to establish this to all call sites with high confidence. These methods are publicly available. There is no known high-level use case to trigger this error, but the fix is easy, and makes the code safer.

Also, unit tests were added to the CChain class, filling a gap.

Changes:

  • Add basic unit tests for CChain class methods
  • Add a nullptr-check to CChain::Contains()

Alternative. I have considered changing Contains() to take a reference instead of pointer, however, when applying that to various methods, it grew to a much bigger changeset -- see #34440. Having in mind the friction of larger PRs, I think the present minimal one-check solution (with the tests) makes sense on its own.

This change is remotely related to and indirectly triggered by #32875 .

@DrahtBot

DrahtBot commented Jan 27, 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/34416.

Reviews

See the guideline for information on the review process.

Type Reviewers
ACK sedited
Stale ACK HowHsu

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:

  • #34440 (refactor: Change CChain methods to use references, add tests by optout21)

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:

  • // Call with non-tip & tip blocks, and with nulltr -> // Call with non-tip & tip blocks, and with nullptr [“nulltr” is a misspelling; it should be “nullptr” to match the C++ token and avoid confusion.]

2026-03-25 05:21:17

@optout21
optout21 marked this pull request as ready for review January 27, 2026 07:31
Comment thread src/net_processing.cpp Outdated
Comment on lines +1923 to +1926
bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
{
AssertLockHeld(cs_main);
if (!pindex) return false;

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 this goes in the wrong direction. All call sites have checked against nullptr, and there should never be a reason to call this with nullptr, so this seems it should be a reference. Just like BlockRequested and FetchBlock take a reference.

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.

Following this feedback, I will reconsider the switch to pass-by-reference. As mentioned in the description, I started in that direction, but was concerned about consistency.
For consistency, it makes sense to also change the other methods (e.g. Next()), increasing the scope. Const input pointer parameters are relatively easy to change to pass-by-reference; but return values where nullptr is a valid option should be changed to std::option<&...>. These end up in a larger changeset (arguably not adding much value).

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.

Well, i haven't looked into the lower level chain util methods. For some methods, it could make sense to accept a pointer. My comment was mostly about BlockRequestAllowed, and other similar high level functions that only work on blocks that exist and whose presence has been previously confirmed

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.

bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex*) should be changed to bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex&)

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.

Being done in 6539829 ( #34440 )

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 don't understand why the some line of code should be changed, only to revert it in the next commit. Please submit 6539829321aa13b4afb8d898a62eb3be382607c0 as a separate pull request

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.

also, the name pindex should probably be changed to block_index (or so), like in the function immediately below

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.

i don't understand why the some line of code should be changed, only to revert it in the next commit. Please submit 6539829 as a separate pull request

I can do it in a separate PR, should be trivial.
The add/remove is a side-effect of independent commits: one commit changed the method called from here (Contains), so a null check had to be added before the call. Then when this method has also been change to take a reference input, the check is no longer needed. (The check moved outwards.)

@optout21 optout21 Feb 5, 2026 •

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.

Note: BlockRequestAllowed change has been done in #34464.

@optout21

Copy link
Copy Markdown
Contributor Author

I'm exploring the option to use references, but I've decided to keep this simple PR as first step.

As suggested, I look into using references instead of pointers. Howerver, that is a bigger refactor. I think the minimal change (one extra check) and unit tests from this PR make sense in isolation, as the bigger change will be heavier. Draft PR #34440 opened. I will strip this one a bit more.
CC: @maflcko

@optout21
optout21 marked this pull request as ready for review January 29, 2026 11:16
@optout21

Copy link
Copy Markdown
Contributor Author

Marked ready for review.

Comment thread src/net_processing.cpp Outdated
Comment on lines +1923 to +1926
bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex* pindex)
{
AssertLockHeld(cs_main);
if (!pindex) return false;

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.

bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex*) should be changed to bool PeerManagerImpl::BlockRequestAllowed(const CBlockIndex&)

Comment thread src/test/chain_tests.cpp Resolved
@HowHsu

HowHsu commented Feb 5, 2026

Copy link
Copy Markdown
Contributor

test ACK 0c2df01

fanquake added a commit that referenced this pull request Feb 5, 2026
1f8f7d4 Change BlockRequestAllowed() to take ref (optout)

Pull request description:

  As [suggested here](#34416 (comment)), a minor refactor of `PeerManagerImpl::BlockRequestAllowed()` to take reference parameter (instead of pointer). The motivation is to make the code safer, by minimizing the risk of null-dereference, and to be more consistent.
  The change is local to the `PeerManagerImpl::BlockRequestAllowed()` class.
  Related to #34440.

ACKs for top commit:
  maflcko:
    review ACK 1f8f7d4 🎐
  l0rinc:
    tested ACK 1f8f7d4
  stickies-v:
    ACK 1f8f7d4

Tree-SHA512: 9c2de2d3e7d067e018db7ec54c79f512ccc1da54574d4fb362f6697ee6e235783779d7094cf20856cd34e08a1dbc74609d8351fe7b2287cd8ec0c836ef07be19
@optout21

optout21 commented Feb 5, 2026

Copy link
Copy Markdown
Contributor Author

Rebased, following merging of #34464 .
One adaptation became obsolete: the added nullptr-check in PeerManagerImpl::BlockRequestAllowed() is no longer needed, as the input parameter has been changed to a reference (in #34464). The file src/net_processing.cpp is no longer in the changeset.
0c2df01acda5891e5c2cea89753ffb5715b2f287..6c3a91f9cefe28a9c7a59963a51c2d64d8c005a2
Ready for (re)review.

@HowHsu

HowHsu commented Feb 7, 2026 •

Copy link
Copy Markdown
Contributor

ACK 6c3a91f9cefe28a9c7a59963a51c2d64d8c005a2

By the way, the CI test failed not because of the PR code.

Comment thread src/test/chain_tests.cpp
BOOST_CHECK_EQUAL(chain_2.Next(&genesis), &bi1);
BOOST_CHECK_EQUAL(chain_2.Next(&bi1), nullptr);
}
}

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.

This test seems overly verbose to me, and I don't think it is meaningfully documenting anything either. We have a test that exercises the block index below, maybe extend that instead?

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.

The existing chain_test() is a rather specific use case, and it doesn't use CChain at all, therefore I would not combine with that.
What I prefer to do is to remove some tests, and rearrange the calls by called function, and keep only one for each different case. I see some value even in basic tests, such as "what happens if Next() is called with nullptr?" or "What happens if indexer is called with a non-existing index?".
But if you prefer, I can remove some more, keep only the nullptr-input ones, or even none.

Comment thread src/chain.h Outdated
@@ -410,7 +410,9 @@ class CChain
/** Efficiently check whether a block is present in this chain. */
bool Contains(const CBlockIndex* pindex) const
{
return (*this)[pindex->nHeight] == pindex;
if (pindex)
return (*this)[pindex->nHeight] == pindex;

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.

This should either be on the same line as the condition or wrapped in braces per the style guide.

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. (I was following the style of the surrounding code, but better to follow the style guide.)

Add basic unit tests to the `CChain` class, filling a gap.
The `CChain::Contains()` method dereferences its input without checking,
potentially resulting in nullptr-dereference if invoked with `nullptr`.
The `Next()` method can also trigger this. Avoid the memory access
violation by adding an extra check for the `pindex` input.
The result is `false` for `nullptr` input.
@optout21

Copy link
Copy Markdown
Contributor Author

Minor rework following review comments:

  • Reduced the number of test calls, rearranged the calls by called function, kept only one call for each different case.
  • Also rebased to recent master.

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

@DrahtBot
DrahtBot requested a review from HowHsu March 25, 2026 09:12
@sedited
sedited requested review from hodlinator and removed request for HowHsu March 25, 2026 09:12
Comment thread src/chain.h
/** Efficiently check whether a block is present in this chain. */
bool Contains(const CBlockIndex* pindex) const
{
if (!pindex) return false;

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.

I do not agree with adding this presently redundant guard. Existing code of master never calls Contains() with nullptr, otherwise it would have crashed.

Much more in favor of #34440.

@DrahtBot
DrahtBot requested a review from HowHsu March 26, 2026 22:31
Comment thread src/test/chain_tests.cpp

} // namespace

BOOST_AUTO_TEST_CASE(cchain_basic_tests)

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.

If you keep this PR over the other one, please consider the suggestions from #34440 (comment)

@optout21

Copy link
Copy Markdown
Contributor Author

Update: #34440 is a more complete improvement, and there has been some opinions in favor of that. However, I still keep this PR open, as a more limited-scope change (easier to review).
There are some minor changes from #34440 that should be applied here as well (for the tests); I will apply them when a need arises to do changes to this PR.

@optout21
optout21 marked this pull request as draft April 21, 2026 11:56
achow101 added a commit that referenced this pull request Apr 22, 2026
…tests

7c75244 Change pindexMostWork parameter of ActivateBestChainStep() to reference (optout)
c5eb283 Change CChain::FindFork() to take ref (optout)
20b58e2 Change CChain::Next() to take reference (optout)
fe2d6e2 Change CChain::Contains() to take reference (optout)
db56bcd test: Add CChain::FindFork() tests (optout)
8333abd test: Add CChain basic tests (optout)

Pull request description:

  Refactor `CChain` methods (`Contains()`, `Next()`, `FindFork()`) to use references instead of pointers, to minimize the risk of accidental `nullptr` dereference (memory access violation). Also add missing unit tests to the `CChain` class.

  The `CChain::Contains()` method (in `src/chain.h`) dereferences its input without checking. The `Next()` method also calls into this with a `nullptr` if invoked with `nullptr`. While most call sites have indirect guarantee that the input is not `nullptr`, it's not easy to establish this to all call sites with high confidence. These methods are publicly available. There is no known high-level use case to trigger this error, but the fix is easy, and makes the code safer.

  Changes:

  - Add basic unit tests for `CChain` class methods
  - Add unit tests for `CChain::FindFork()`
  - Change `CChain::Contains()` to take reference
  - Change `CChain::Next()` to take reference
  - Change `CChain::FindFork()` to take reference
  - Change `pindexMostWork` parameter of `ActivateBestChainStep()` to reference
  - Rename changed parameters (`* pindex` --> `& index`)

  Alternative. A simpler change is to stick with pointers, with extra checks where needed, see #34416 .

  This change is remotely related to and indirectly triggered by #32875 .

  Further ideas, not considered in this PR:

  - Change `InvalidateBlock()` and `PreciousBlock()` to take references.
  - Change `CChain` internals to store references instead of pointers
  - Change CChain to always have at least one element (genesis), that way there is always genesis and tip.
  - Check related methods to return reference (guaranteed non-null) -- `FindFork`, `FindEarliestAtLeast`, `FindForkInGlobalIndex`, `blockman.AddToBlockIndex`, etc.

ACKs for top commit:
  l0rinc:
    reACK 7c75244
  maflcko:
    re-review ACK 7c75244 🌅
  achow101:
    ACK 7c75244
  hodlinator:
    re-ACK 7c75244

Tree-SHA512: 122f40120058f7e1f0273b3afed9c54966c05f06b6f2fee45bc48430617f24a5e4320a9bb7bb0ac986f2accfa22fabae5cc941b949758ddca2e9fcd472b46c33
@optout21

Copy link
Copy Markdown
Contributor Author

This has became unnecessary after #34440 landed -- tests are included there, Contains() is changed to take only non-null references. Closing.

@DrahtBot

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

@optout21 optout21 closed this Apr 23, 2026
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Jun 28, 2026
… (minor refactor)

e3a3963 Change BlockRequestAllowed() to take ref (optout)

Pull request description:

  As [suggested here](bitcoin/bitcoin#34416 (comment)), a minor refactor of `PeerManagerImpl::BlockRequestAllowed()` to take reference parameter (instead of pointer). The motivation is to make the code safer, by minimizing the risk of null-dereference, and to be more consistent.
  The change is local to the `PeerManagerImpl::BlockRequestAllowed()` class.
  Related to #34440.

ACKs for top commit:
  maflcko:
    review ACK e3a3963 🎐
  l0rinc:
    tested ACK e3a3963
  stickies-v:
    ACK e3a3963

Tree-SHA512: 9c2de2d3e7d067e018db7ec54c79f512ccc1da54574d4fb362f6697ee6e235783779d7094cf20856cd34e08a1dbc74609d8351fe7b2287cd8ec0c836ef07be19
BigcoinBGC pushed a commit to BigcoinBGC/bigcoin that referenced this pull request Jun 30, 2026
… (minor refactor)

2e0df69 Change BlockRequestAllowed() to take ref (optout)

Pull request description:

  As [suggested here](bitcoin/bitcoin#34416 (comment)), a minor refactor of `PeerManagerImpl::BlockRequestAllowed()` to take reference parameter (instead of pointer). The motivation is to make the code safer, by minimizing the risk of null-dereference, and to be more consistent.
  The change is local to the `PeerManagerImpl::BlockRequestAllowed()` class.
  Related to #34440.

ACKs for top commit:
  maflcko:
    review ACK 2e0df69 🎐
  l0rinc:
    tested ACK 2e0df69
  stickies-v:
    ACK 2e0df69

Tree-SHA512: 9c2de2d3e7d067e018db7ec54c79f512ccc1da54574d4fb362f6697ee6e235783779d7094cf20856cd34e08a1dbc74609d8351fe7b2287cd8ec0c836ef07be19
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Aug 19, 2026
… (minor refactor)

1f8f7d477ae0d33bd96f7936889c17bd40805fb9 Change BlockRequestAllowed() to take ref (optout)

Pull request description:

  As [suggested here](bitcoin/bitcoin#34416 (comment)), a minor refactor of `PeerManagerImpl::BlockRequestAllowed()` to take reference parameter (instead of pointer). The motivation is to make the code safer, by minimizing the risk of null-dereference, and to be more consistent.
  The change is local to the `PeerManagerImpl::BlockRequestAllowed()` class.
  Related to #34440.

ACKs for top commit:
  maflcko:
    review ACK 1f8f7d477ae0d33bd96f7936889c17bd40805fb9 🎐
  l0rinc:
    tested ACK 1f8f7d477ae0d33bd96f7936889c17bd40805fb9
  stickies-v:
    ACK 1f8f7d477ae0d33bd96f7936889c17bd40805fb9

Tree-SHA512: 9c2de2d3e7d067e018db7ec54c79f512ccc1da54574d4fb362f6697ee6e235783779d7094cf20856cd34e08a1dbc74609d8351fe7b2287cd8ec0c836ef07be19
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.

7 participants