Skip to content

Commit 6fba25e

Browse files
committed
Merge pull request #4420 from sipa/skiplist
Add a skiplist to the CBlockIndex structure.
2 parents ac26571 + 236982c commit 6fba25e

File tree

5 files changed

+163
-2
lines changed

5 files changed

+163
-2
lines changed

src/Makefile.test.include

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ BITCOIN_TESTS =\
4747
test/script_tests.cpp \
4848
test/serialize_tests.cpp \
4949
test/sigopcount_tests.cpp \
50+
test/skiplist_tests.cpp \
5051
test/test_bitcoin.cpp \
5152
test/transaction_tests.cpp \
5253
test/uint256_tests.cpp \

src/main.cpp

Lines changed: 104 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,10 @@ struct CNodeState {
207207
std::string name;
208208
// List of asynchronously-determined block rejections to notify this peer about.
209209
std::vector<CBlockReject> rejects;
210+
// The best known block we know this peer has announced.
211+
CBlockIndex *pindexBestKnownBlock;
212+
// The hash of the last unknown block this peer has announced.
213+
uint256 hashLastUnknownBlock;
210214
list<QueuedBlock> vBlocksInFlight;
211215
int nBlocksInFlight;
212216
list<uint256> vBlocksToDownload;
@@ -217,6 +221,8 @@ struct CNodeState {
217221
CNodeState() {
218222
nMisbehavior = 0;
219223
fShouldBan = false;
224+
pindexBestKnownBlock = NULL;
225+
hashLastUnknownBlock = uint256(0);
220226
nBlocksToDownload = 0;
221227
nBlocksInFlight = 0;
222228
nLastBlockReceive = 0;
@@ -313,6 +319,39 @@ void MarkBlockAsInFlight(NodeId nodeid, const uint256 &hash) {
313319
mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
314320
}
315321

322+
/** Check whether the last unknown block a peer advertized is not yet known. */
323+
void ProcessBlockAvailability(NodeId nodeid) {
324+
CNodeState *state = State(nodeid);
325+
assert(state != NULL);
326+
327+
if (state->hashLastUnknownBlock != 0) {
328+
map<uint256, CBlockIndex*>::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
329+
if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
330+
if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
331+
state->pindexBestKnownBlock = itOld->second;
332+
state->hashLastUnknownBlock = uint256(0);
333+
}
334+
}
335+
}
336+
337+
/** Update tracking information about which blocks a peer is assumed to have. */
338+
void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
339+
CNodeState *state = State(nodeid);
340+
assert(state != NULL);
341+
342+
ProcessBlockAvailability(nodeid);
343+
344+
map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(hash);
345+
if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
346+
// An actually better block was announced.
347+
if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
348+
state->pindexBestKnownBlock = it->second;
349+
} else {
350+
// An unknown block was announced; just assume that the latest one is the best one.
351+
state->hashLastUnknownBlock = hash;
352+
}
353+
}
354+
316355
} // anon namespace
317356

318357
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
@@ -321,6 +360,7 @@ bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
321360
if (state == NULL)
322361
return false;
323362
stats.nMisbehavior = state->nMisbehavior;
363+
stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
324364
return true;
325365
}
326366

@@ -374,8 +414,11 @@ CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
374414
break;
375415
// Exponentially larger steps back, plus the genesis block.
376416
int nHeight = std::max(pindex->nHeight - nStep, 0);
417+
// Jump back quickly to the same height as the chain.
418+
if (pindex->nHeight > nHeight)
419+
pindex = pindex->GetAncestor(nHeight);
377420
// In case pindex is not in this chain, iterate pindex->pprev to find blocks.
378-
while (pindex->nHeight > nHeight && !Contains(pindex))
421+
while (!Contains(pindex))
379422
pindex = pindex->pprev;
380423
// If pindex is in this chain, use direct height-based access.
381424
if (pindex->nHeight > nHeight)
@@ -402,6 +445,8 @@ CBlockIndex *CChain::FindFork(const CBlockLocator &locator) const {
402445
}
403446

404447
CBlockIndex *CChain::FindFork(CBlockIndex *pindex) const {
448+
if (pindex->nHeight > Height())
449+
pindex = pindex->GetAncestor(Height());
405450
while (pindex && !Contains(pindex))
406451
pindex = pindex->pprev;
407452
return pindex;
@@ -2111,6 +2156,7 @@ CBlockIndex* AddToBlockIndex(CBlockHeader& block)
21112156
{
21122157
pindexNew->pprev = (*miPrev).second;
21132158
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2159+
pindexNew->BuildSkip();
21142160
}
21152161
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork();
21162162
pindexNew->RaiseValidity(BLOCK_VALID_TREE);
@@ -2468,6 +2514,55 @@ bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, uns
24682514
return (nFound >= nRequired);
24692515
}
24702516

2517+
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
2518+
int static inline InvertLowestOne(int n) { return n & (n - 1); }
2519+
2520+
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
2521+
int static inline GetSkipHeight(int height) {
2522+
if (height < 2)
2523+
return 0;
2524+
2525+
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
2526+
// but the following expression seems to perform well in simulations (max 110 steps to go back
2527+
// up to 2**18 blocks).
2528+
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
2529+
}
2530+
2531+
CBlockIndex* CBlockIndex::GetAncestor(int height)
2532+
{
2533+
if (height > nHeight || height < 0)
2534+
return NULL;
2535+
2536+
CBlockIndex* pindexWalk = this;
2537+
int heightWalk = nHeight;
2538+
while (heightWalk > height) {
2539+
int heightSkip = GetSkipHeight(heightWalk);
2540+
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
2541+
if (heightSkip == height ||
2542+
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
2543+
heightSkipPrev >= height))) {
2544+
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
2545+
pindexWalk = pindexWalk->pskip;
2546+
heightWalk = heightSkip;
2547+
} else {
2548+
pindexWalk = pindexWalk->pprev;
2549+
heightWalk--;
2550+
}
2551+
}
2552+
return pindexWalk;
2553+
}
2554+
2555+
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
2556+
{
2557+
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
2558+
}
2559+
2560+
void CBlockIndex::BuildSkip()
2561+
{
2562+
if (pprev)
2563+
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
2564+
}
2565+
24712566
void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd)
24722567
{
24732568
AssertLockHeld(cs_main);
@@ -2818,6 +2913,8 @@ bool static LoadBlockIndexDB()
28182913
setBlockIndexValid.insert(pindex);
28192914
if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
28202915
pindexBestInvalid = pindex;
2916+
if (pindex->pprev)
2917+
pindex->BuildSkip();
28212918
}
28222919

28232920
// Load block file info
@@ -3613,6 +3710,9 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
36133710
PushGetBlocks(pfrom, chainActive.Tip(), GetOrphanRoot(inv.hash));
36143711
}
36153712

3713+
if (inv.type == MSG_BLOCK)
3714+
UpdateBlockAvailability(pfrom->GetId(), inv.hash);
3715+
36163716
// Track requests for our stuff
36173717
g_signals.Inventory(inv.hash);
36183718
}
@@ -4359,6 +4459,9 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
43594459
pto->fDisconnect = true;
43604460
}
43614461

4462+
// Update knowledge of peer's block availability.
4463+
ProcessBlockAvailability(pto->GetId());
4464+
43624465
//
43634466
// Message: getdata (blocks)
43644467
//

src/main.h

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
185185

186186
struct CNodeStateStats {
187187
int nMisbehavior;
188+
int nSyncHeight;
188189
};
189190

190191
struct CDiskBlockPos
@@ -676,6 +677,9 @@ class CBlockIndex
676677
// pointer to the index of the predecessor of this block
677678
CBlockIndex* pprev;
678679

680+
// pointer to the index of some further predecessor of this block
681+
CBlockIndex* pskip;
682+
679683
// height of the entry in the chain. The genesis block has height 0
680684
int nHeight;
681685

@@ -715,6 +719,7 @@ class CBlockIndex
715719
{
716720
phashBlock = NULL;
717721
pprev = NULL;
722+
pskip = NULL;
718723
nHeight = 0;
719724
nFile = 0;
720725
nDataPos = 0;
@@ -736,6 +741,7 @@ class CBlockIndex
736741
{
737742
phashBlock = NULL;
738743
pprev = NULL;
744+
pskip = NULL;
739745
nHeight = 0;
740746
nFile = 0;
741747
nDataPos = 0;
@@ -868,9 +874,14 @@ class CBlockIndex
868874
}
869875
return false;
870876
}
871-
};
872877

878+
// Build the skiplist pointer for this entry.
879+
void BuildSkip();
873880

881+
// Efficiently find an ancestor of this block.
882+
CBlockIndex* GetAncestor(int height);
883+
const CBlockIndex* GetAncestor(int height) const;
884+
};
874885

875886
/** Used to marshal pointers into hashes for db storage. */
876887
class CDiskBlockIndex : public CBlockIndex

src/rpcnet.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ Value getpeerinfo(const Array& params, bool fHelp)
134134
obj.push_back(Pair("startingheight", stats.nStartingHeight));
135135
if (fStateStats) {
136136
obj.push_back(Pair("banscore", statestats.nMisbehavior));
137+
obj.push_back(Pair("syncheight", statestats.nSyncHeight));
137138
}
138139
obj.push_back(Pair("syncnode", stats.fSyncNode));
139140

src/test/skiplist_tests.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright (c) 2014 The Bitcoin Core developers
2+
// Distributed under the MIT/X11 software license, see the accompanying
3+
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4+
5+
#include <boost/test/unit_test.hpp>
6+
#include <vector>
7+
#include "main.h"
8+
#include "util.h"
9+
10+
11+
#define SKIPLIST_LENGTH 300000
12+
13+
BOOST_AUTO_TEST_SUITE(skiplist_tests)
14+
15+
BOOST_AUTO_TEST_CASE(skiplist_test)
16+
{
17+
std::vector<CBlockIndex> vIndex(SKIPLIST_LENGTH);
18+
19+
for (int i=0; i<SKIPLIST_LENGTH; i++) {
20+
vIndex[i].nHeight = i;
21+
vIndex[i].pprev = (i == 0) ? NULL : &vIndex[i - 1];
22+
vIndex[i].BuildSkip();
23+
}
24+
25+
for (int i=0; i<SKIPLIST_LENGTH; i++) {
26+
if (i > 0) {
27+
BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]);
28+
BOOST_CHECK(vIndex[i].pskip->nHeight < i);
29+
} else {
30+
BOOST_CHECK(vIndex[i].pskip == NULL);
31+
}
32+
}
33+
34+
for (int i=0; i < 1000; i++) {
35+
int from = insecure_rand() % (SKIPLIST_LENGTH - 1);
36+
int to = insecure_rand() % (from + 1);
37+
38+
BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]);
39+
BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]);
40+
BOOST_CHECK(vIndex[from].GetAncestor(0) == &vIndex[0]);
41+
}
42+
}
43+
44+
BOOST_AUTO_TEST_SUITE_END()
45+

0 commit comments

Comments
 (0)