1 // Copyright (c) 2011 The Bitcoin developers
2 // Copyright (c) 2011-2012 The PPCoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include <boost/assign/list_of.hpp> // for 'map_list_of()'
7 #include <boost/foreach.hpp>
10 #include "checkpoints.h"
14 typedef std::map<int, uint256> MapCheckpoints; // hardened checkpoints
17 // What makes a good checkpoint block?
18 // + Is surrounded by blocks with reasonable timestamps
19 // (no blocks before with a timestamp after, none after with
21 // + Contains no strange transactions
23 static MapCheckpoints mapCheckpoints =
24 boost::assign::map_list_of
25 ( 0, hashGenesisBlock )
26 ; // ppcoin: no checkpoint yet; to be created in future releases
28 bool CheckHardened(int nHeight, const uint256& hash)
30 if (fTestNet) return true; // Testnet has no checkpoints
32 MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
33 if (i == mapCheckpoints.end()) return true;
34 return hash == i->second;
37 int GetTotalBlocksEstimate()
39 if (fTestNet) return 0;
41 return mapCheckpoints.rbegin()->first;
44 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
46 if (fTestNet) return NULL;
49 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
51 const uint256& hash = i.second;
52 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
53 if (t != mapBlockIndex.end())
59 // ppcoin: synchronized checkpoint (centrally broadcasted)
60 uint256 hashSyncCheckpoint;
61 CSyncCheckpoint checkpointMessage;
62 CSyncCheckpoint checkpointMessagePending;
63 uint256 hashInvalidCheckpoint = 0;
64 CCriticalSection cs_hashSyncCheckpoint;
66 // ppcoin: get last synchronized checkpoint
67 CBlockIndex* GetLastSyncCheckpoint()
69 CRITICAL_BLOCK(cs_hashSyncCheckpoint)
71 if (!mapBlockIndex.count(hashSyncCheckpoint))
72 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
74 return mapBlockIndex[hashSyncCheckpoint];
79 // ppcoin: only descendant of current sync-checkpoint is allowed
80 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
82 if (!mapBlockIndex.count(hashSyncCheckpoint))
83 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
84 if (!mapBlockIndex.count(hashCheckpoint))
85 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
87 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
88 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
90 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
92 // Received an older checkpoint, trace back from current checkpoint
93 // to the same height of the received checkpoint to verify
94 // that current checkpoint should be a descendant block
95 CBlockIndex* pindex = pindexSyncCheckpoint;
96 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
97 if (!(pindex = pindex->pprev))
98 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
99 if (pindex->GetBlockHash() != hashCheckpoint)
101 hashInvalidCheckpoint = hashCheckpoint;
102 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
104 return false; // ignore older checkpoint
107 // Received checkpoint should be a descendant block of the current
108 // checkpoint. Trace back to the same height of current checkpoint
110 CBlockIndex* pindex = pindexCheckpointRecv;
111 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
112 if (!(pindex = pindex->pprev))
113 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
114 if (pindex->GetBlockHash() != hashSyncCheckpoint)
116 hashInvalidCheckpoint = hashCheckpoint;
117 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
122 bool AcceptPendingSyncCheckpoint()
124 CRITICAL_BLOCK(cs_hashSyncCheckpoint)
126 if ((!checkpointMessagePending.IsNull()) && mapBlockIndex.count(checkpointMessagePending.hashCheckpoint))
128 if (!ValidateSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
130 checkpointMessagePending.SetNull();
135 CBlockIndex* pindexCheckpoint = mapBlockIndex[checkpointMessagePending.hashCheckpoint];
136 if (!pindexCheckpoint->IsInMainChain())
139 if (!Reorganize(txdb, pindexCheckpoint))
142 hashInvalidCheckpoint = checkpointMessagePending.hashCheckpoint;
143 return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", checkpointMessagePending.hashCheckpoint.ToString().c_str());
148 if (!txdb.WriteSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
151 return error("AcceptPendingSyncCheckpoint() : failed to write to db sync checkpoint %s\n", checkpointMessagePending.hashCheckpoint.ToString().c_str());
153 if (!txdb.TxnCommit())
154 return error("AcceptPendingSyncCheckpoint() : failed to commit to db sync checkpoint %s\n", checkpointMessagePending.hashCheckpoint.ToString().c_str());
157 hashSyncCheckpoint = checkpointMessagePending.hashCheckpoint;
158 checkpointMessage = checkpointMessagePending;
159 checkpointMessagePending.SetNull();
160 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
161 // relay the checkpoint
162 CRITICAL_BLOCK(cs_hashSyncCheckpoint)
163 BOOST_FOREACH(CNode* pnode, vNodes)
164 checkpointMessage.RelayTo(pnode);
172 uint256 AutoSelectSyncCheckpoint()
174 // select block roughly 8 hours ago
175 CBlockIndex *pindex = mapBlockIndex[hashSyncCheckpoint];
176 while (pindex->pnext && pindex->pnext->GetBlockTime() + AUTO_CHECKPOINT_MIN_SPAN <= GetAdjustedTime())
177 pindex = pindex->pnext;
178 return pindex->GetBlockHash();
181 // Check against synchronized checkpoint
182 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
184 if (fTestNet) return true; // Testnet has no checkpoints
185 int nHeight = pindexPrev->nHeight + 1;
187 CRITICAL_BLOCK(cs_hashSyncCheckpoint)
189 // sync-checkpoint should always be accepted block
190 assert(mapBlockIndex.count(hashSyncCheckpoint));
191 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
193 if (nHeight > pindexSync->nHeight)
195 // trace back to same height as sync-checkpoint
196 const CBlockIndex* pindex = pindexPrev;
197 while (pindex->nHeight > pindexSync->nHeight)
198 if (!(pindex = pindex->pprev))
199 return error("CheckSync: pprev null - block index structure failure");
200 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
201 return false; // only descendant of sync-checkpoint can pass check
203 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
204 return false; // same height with sync-checkpoint
205 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
206 return false; // lower height than sync-checkpoint
211 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
213 CRITICAL_BLOCK(cs_hashSyncCheckpoint)
215 if (checkpointMessagePending.IsNull())
217 if (hashBlock == checkpointMessagePending.hashCheckpoint)
219 if (mapOrphanBlocks.count(checkpointMessagePending.hashCheckpoint)
220 && hashBlock == WantedByOrphan(mapOrphanBlocks[checkpointMessagePending.hashCheckpoint]))
226 // ppcoin: automatic checkpoint (represented by height of checkpoint)
227 int nAutoCheckpoint = 0;
228 int nBranchPoint = 0; // branch point to alternative branch
230 // ppcoin: check automatic checkpoint
231 // To pass the check:
232 // - All ancestors (including the block itself) have block index already
233 // - The immediate ancestor in main chain must not have height less than
235 bool CheckAuto(const CBlockIndex *pindex)
239 if (pindex->IsInMainChain())
241 if (pindex->nHeight >= nAutoCheckpoint)
245 nBranchPoint = pindex->nHeight;
246 return error("Checkpoints: new block on alternative branch at height=%d before auto checkpoint at height=%d", pindex->nHeight, nAutoCheckpoint);
250 pindex = pindex->pprev;
252 return error("Checkpoints: failed to find any ancestor on main chain for the new block - internal error");
255 // ppcoin: get next chain checkpoint
256 int GetNextChainCheckpoint(const CBlockIndex *pindexLast)
259 CBigNum bnTargetMax = 0; // max target of all blocks since checkpoint
260 CBigNum bnTargetMin = 0; // min target of all candidate checkpoints
261 int nMinTargetHeight = 0; // min target height of candidate checkpoints
262 int nCheckpointMin = 0; // minimum candidate checkpoint
263 int nCheckpointMax = 0; // maximum candidate checkpoint
264 int nDepth = pindexLast->nHeight - pindexLast->nCheckpoint;
265 const CBlockIndex *pindex = pindexLast;
266 while (nDepth >= 0 && pindex)
268 bnTarget.SetCompact(pindex->nBits);
269 if (bnTarget > bnTargetMax)
270 bnTargetMax = bnTarget;
271 if (nCheckpointMax > 0 && bnTarget < bnTargetMin)
273 bnTargetMin = bnTarget;
274 nMinTargetHeight = pindex->nHeight;
276 if (nCheckpointMax == 0 && pindexLast->GetBlockTime() - pindex->GetBlockTime() > AUTO_CHECKPOINT_MIN_SPAN)
278 nCheckpointMax = pindex->nHeight;
279 bnTargetMin.SetCompact(pindex->nBits);
280 nMinTargetHeight = pindex->nHeight;
282 if (pindexLast->GetBlockTime() - pindex->GetBlockTime() < AUTO_CHECKPOINT_MAX_SPAN)
283 nCheckpointMin = pindex->nHeight;
284 pindex = pindex->pprev;
288 assert (nDepth == -1); // arrive at chain checkpoint now
290 printf("Checkpoints: min=%d max=%d tminheight=%d tmin=0x%08x tmax=0x%08x\n",
291 nCheckpointMin, nCheckpointMax, nMinTargetHeight,
292 bnTargetMin.GetCompact(), bnTargetMax.GetCompact());
293 if (nCheckpointMax == 0) // checkpoint stays if max candidate not found
294 return pindexLast->nCheckpoint;
296 if (bnTargetMin * 100 > bnTargetMax * 90)
297 return nCheckpointMax;
298 if (bnTarget * 100 > bnTargetMax * 90)
299 return nMinTargetHeight;
301 return nCheckpointMin;
304 // ppcoin: get next auto checkpoint from the new chain checkpoint
305 int GetNextAutoCheckpoint(int nCheckpoint)
307 return (std::max(nAutoCheckpoint, nCheckpoint));
310 // ppcoin: advance to next automatic checkpoint
311 void AdvanceAutoCheckpoint(int nCheckpoint)
313 nAutoCheckpoint = GetNextAutoCheckpoint(nCheckpoint);
314 printf("Checkpoints: auto checkpoint now at height=%d\n", nAutoCheckpoint);
317 // ppcoin: reset auto checkpoint
318 bool ResetAutoCheckpoint(int nCheckpoint)
320 if (nCheckpoint <= 0 || nCheckpoint > nBestHeight)
321 return error("ResetAutoCheckpoint() : new checkpoint invalid");
322 if (nCheckpoint >= nAutoCheckpoint)
323 return error("ResetAutoCheckpoint() : new checkpoint not earlier than current auto checkpoint");
326 if (!txdb.WriteAutoCheckpoint(nCheckpoint, true))
327 return error("ResetAutoCheckpoint() : database write failed");
328 if (!txdb.TxnCommit())
329 return error("ResetAutoCheckpoint() : database commit failed");
330 nAutoCheckpoint = nCheckpoint;
331 nBranchPoint = 0; // clear branch point
333 // clear ban list to accept alternative branches
334 CRITICAL_BLOCK(cs_vNodes)
336 BOOST_FOREACH(CNode* pnode, vNodes)
337 pnode->ClearBanned();
344 // ppcoin: sync-checkpoint master key
345 const std::string CSyncCheckpoint::strMasterPubKey = "0424f20205e5da98ba632bbd278a11a6499585f62bfb2c782377ef59f0251daab8085fc31471bcb8180bc75ed0fa41bb50c7c084511d54015a3a5241d645c7268a";
347 // ppcoin: verify signature of sync-checkpoint message
348 bool CSyncCheckpoint::CheckSignature()
351 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
352 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
353 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
354 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
356 // Now unserialize the data
357 CDataStream sMsg(vchMsg);
358 sMsg >> *(CUnsignedSyncCheckpoint*)this;
362 // ppcoin: process synchronized checkpoint
363 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
365 if (!CheckSignature())
368 CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)
370 if (!mapBlockIndex.count(hashCheckpoint))
372 // We haven't received the checkpoint chain, keep the checkpoint as pending
373 Checkpoints::checkpointMessagePending = *this;
374 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
375 // Ask this guy to fill in what we're missing
378 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
379 // ask directly as well in case rejected earlier by duplicate
380 // proof-of-stake because getblocks may not get it this time
381 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
386 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
390 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
391 if (!pindexCheckpoint->IsInMainChain())
393 // checkpoint chain received but not yet main chain
395 if (!Reorganize(txdb, pindexCheckpoint))
398 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
399 return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
404 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
407 return error("ProcessSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
409 if (!txdb.TxnCommit())
410 return error("ProcessSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
413 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
414 Checkpoints::checkpointMessage = *this;
415 Checkpoints::checkpointMessagePending.SetNull();
416 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());