Skip to content

Commit

Permalink
Fix code constness in CBlockIndex::GetAncestor() overloads
Browse files Browse the repository at this point in the history
Make the non-const overload of CBlockIndex::GetAncestor() reuse the
const overload implementation instead of the other way around. This way,
the constness of the const overload implementation is guaranteed. The
other way around, it was possible to implement the non-const overload in
a way which mutates the object, and since that implementation would be
called even for const objects (due to the reuse), we would get undefined
behavior.
  • Loading branch information
danra authored and random-zebra committed Jul 25, 2021
1 parent 65e3f4e commit a346262
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/chain.cpp
Expand Up @@ -85,12 +85,13 @@ int static inline GetSkipHeight(int height)
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}

CBlockIndex* CBlockIndex::GetAncestor(int height)
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
if (height > nHeight || height < 0)
return NULL;
if (height > nHeight || height < 0) {
return nullptr;
}

CBlockIndex* pindexWalk = this;
const CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
Expand All @@ -109,9 +110,9 @@ CBlockIndex* CBlockIndex::GetAncestor(int height)
return pindexWalk;
}

const CBlockIndex* CBlockIndex::GetAncestor(int height) const
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height));
}

void CBlockIndex::BuildSkip()
Expand Down

0 comments on commit a346262

Please sign in to comment.