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
CChainclass methods - Add a nullptr-check to
CChain::Contains() - Add unit tests for
CChain::FindFork(). These are lengthier, and not closely related to the topic of the PR, could be removed, but kept for extra test coverage.
Alternative. I have considered changing Contains() to take a reference instead of pointer, to better express that it cannot take a nullptr input. It’s a viable solution, requires update to only a handful of call sites (solution available on branch cchain-contains1). However, since most CChain logic operates with pointers and pointer comparison, it would break the style, so I dropped this solution.
This change is remotely related to and partly triggered by #32875 .