aboutsummaryrefslogtreecommitdiff
path: root/src/chain.cpp
diff options
context:
space:
mode:
authorPieter Wuille <pieter.wuille@gmail.com>2014-11-23 14:07:38 +0100
committerPieter Wuille <pieter.wuille@gmail.com>2014-12-11 17:39:10 +0100
commit5ea3bc06d501594a36c97e20df2d446e87956aed (patch)
tree9f23ca25180a0be3d7b001e5dc2451f948643180 /src/chain.cpp
parent9dcd524f3248cb4fca5613a3c11dddcc7a0efbd7 (diff)
Move remaining CBlockIndex methods to chain.cpp
Diffstat (limited to 'src/chain.cpp')
-rw-r--r--src/chain.cpp49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/chain.cpp b/src/chain.cpp
index e13c047861..3dbaf5a36a 100644
--- a/src/chain.cpp
+++ b/src/chain.cpp
@@ -57,3 +57,52 @@ const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
pindex = pindex->pprev;
return pindex;
}
+
+/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
+int static inline InvertLowestOne(int n) { return n & (n - 1); }
+
+/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
+int static inline GetSkipHeight(int height) {
+ if (height < 2)
+ return 0;
+
+ // Determine which height to jump back to. Any number strictly lower than height is acceptable,
+ // but the following expression seems to perform well in simulations (max 110 steps to go back
+ // up to 2**18 blocks).
+ return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
+}
+
+CBlockIndex* CBlockIndex::GetAncestor(int height)
+{
+ if (height > nHeight || height < 0)
+ return NULL;
+
+ CBlockIndex* pindexWalk = this;
+ int heightWalk = nHeight;
+ while (heightWalk > height) {
+ int heightSkip = GetSkipHeight(heightWalk);
+ int heightSkipPrev = GetSkipHeight(heightWalk - 1);
+ if (heightSkip == height ||
+ (heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
+ heightSkipPrev >= height))) {
+ // Only follow pskip if pprev->pskip isn't better than pskip->pprev.
+ pindexWalk = pindexWalk->pskip;
+ heightWalk = heightSkip;
+ } else {
+ pindexWalk = pindexWalk->pprev;
+ heightWalk--;
+ }
+ }
+ return pindexWalk;
+}
+
+const CBlockIndex* CBlockIndex::GetAncestor(int height) const
+{
+ return const_cast<CBlockIndex*>(this)->GetAncestor(height);
+}
+
+void CBlockIndex::BuildSkip()
+{
+ if (pprev)
+ pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
+}