From b4058ed9c6e1f23720afa0b383c56a9aaed86dcd Mon Sep 17 00:00:00 2001 From: Dan Raviv Date: Fri, 15 Sep 2017 11:13:25 +0300 Subject: Fix code constness in CBlockIndex::GetAncestor() overloads 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. --- src/chain.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/chain.cpp b/src/chain.cpp index 47acde882e..63e75ccecf 100644 --- a/src/chain.cpp +++ b/src/chain.cpp @@ -80,12 +80,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) + if (height > nHeight || height < 0) { return nullptr; + } - CBlockIndex* pindexWalk = this; + const CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); @@ -106,9 +107,9 @@ CBlockIndex* CBlockIndex::GetAncestor(int height) return pindexWalk; } -const CBlockIndex* CBlockIndex::GetAncestor(int height) const +CBlockIndex* CBlockIndex::GetAncestor(int height) { - return const_cast(this)->GetAncestor(height); + return const_cast(static_cast(this)->GetAncestor(height)); } void CBlockIndex::BuildSkip() -- cgit v1.2.3