Refactor CChain methods (Contains(), Next(), etc.) 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
CChainclass methods - Refactor
CChain::Contains()to take reference - Refactor
CChain::Next()to take reference - Add unit tests for
CChain::FindFork() - Change
PeerManagerImpl::BlockRequestAllowed()to take reference
TODO:
- ? /Change
CChaininternals to store references instead of pointers/ - ? /Explore the change to always have at least one element (genesis), that way there is always genesis and tip./
- Check related methods to change to reference –
FindFork,FindEarliestAtLeast,FindForkInGlobalIndex,blockman.AddToBlockIndex, etc.
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 .