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: only descendant of current sync-checkpoint is allowed
67 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
69 if (!mapBlockIndex.count(hashSyncCheckpoint))
70 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
71 if (!mapBlockIndex.count(hashCheckpoint))
72 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
74 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
75 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
77 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
79 // Received an older checkpoint, trace back from current checkpoint
80 // to the same height of the received checkpoint to verify
81 // that current checkpoint should be a descendant block
82 CBlockIndex* pindex = pindexSyncCheckpoint;
83 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
84 if (!(pindex = pindex->pprev))
85 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
86 if (pindex->GetBlockHash() != hashCheckpoint)
88 hashInvalidCheckpoint = hashCheckpoint;
89 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
91 return false; // ignore older checkpoint
94 // Received checkpoint should be a descendant block of the current
95 // checkpoint. Trace back to the same height of current checkpoint
97 CBlockIndex* pindex = pindexCheckpointRecv;
98 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
99 if (!(pindex = pindex->pprev))
100 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
101 if (pindex->GetBlockHash() != hashSyncCheckpoint)
103 hashInvalidCheckpoint = hashCheckpoint;
104 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
109 bool AcceptPendingSyncCheckpoint()
111 CRITICAL_BLOCK(cs_hashSyncCheckpoint)
113 if ((!checkpointMessagePending.IsNull()) && mapBlockIndex.count(checkpointMessagePending.hashCheckpoint))
115 if (!ValidateSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
117 checkpointMessagePending.SetNull();
122 CBlockIndex* pindexCheckpoint = mapBlockIndex[checkpointMessagePending.hashCheckpoint];
123 if (!pindexCheckpoint->IsInMainChain())
126 if (!Reorganize(txdb, pindexCheckpoint))
129 hashInvalidCheckpoint = checkpointMessagePending.hashCheckpoint;
130 return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", checkpointMessagePending.hashCheckpoint.ToString().c_str());
135 if (!txdb.WriteSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
138 return error("AcceptPendingSyncCheckpoint() : failed to write to db sync checkpoint %s\n", checkpointMessagePending.hashCheckpoint.ToString().c_str());
140 if (!txdb.TxnCommit())
141 return error("AcceptPendingSyncCheckpoint() : failed to commit to db sync checkpoint %s\n", checkpointMessagePending.hashCheckpoint.ToString().c_str());
144 hashSyncCheckpoint = checkpointMessagePending.hashCheckpoint;
145 checkpointMessage = checkpointMessagePending;
146 checkpointMessagePending.SetNull();
147 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
148 // relay the checkpoint
149 CRITICAL_BLOCK(cs_hashSyncCheckpoint)
150 BOOST_FOREACH(CNode* pnode, vNodes)
151 checkpointMessage.RelayTo(pnode);
159 uint256 AutoSelectSyncCheckpoint()
161 // select block roughly 8 hours ago
162 CBlockIndex *pindex = mapBlockIndex[hashSyncCheckpoint];
163 while (pindex->pnext && pindex->pnext->GetBlockTime() + AUTO_CHECKPOINT_MIN_SPAN <= GetAdjustedTime())
164 pindex = pindex->pnext;
165 return pindex->GetBlockHash();
168 // Check against synchronized checkpoint
169 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
171 if (fTestNet) return true; // Testnet has no checkpoints
172 int nHeight = pindexPrev->nHeight + 1;
174 CRITICAL_BLOCK(cs_hashSyncCheckpoint)
176 // sync-checkpoint should always be accepted block
177 assert(mapBlockIndex.count(hashSyncCheckpoint));
178 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
180 if (nHeight > pindexSync->nHeight)
182 // trace back to same height as sync-checkpoint
183 const CBlockIndex* pindex = pindexPrev;
184 while (pindex->nHeight > pindexSync->nHeight)
185 if (!(pindex = pindex->pprev))
186 return error("CheckSync: pprev null - block index structure failure");
187 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
188 return false; // only descendant of sync-checkpoint can pass check
190 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
191 return false; // same height with sync-checkpoint
192 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
193 return false; // lower height than sync-checkpoint
198 bool IsPendingSyncCheckpoint(uint256 hashBlock)
200 CRITICAL_BLOCK(cs_hashSyncCheckpoint)
201 return ((!checkpointMessagePending.IsNull()) && hashBlock == checkpointMessagePending.hashCheckpoint);
204 // ppcoin: automatic checkpoint (represented by height of checkpoint)
205 int nAutoCheckpoint = 0;
206 int nBranchPoint = 0; // branch point to alternative branch
208 // ppcoin: check automatic checkpoint
209 // To pass the check:
210 // - All ancestors (including the block itself) have block index already
211 // - The immediate ancestor in main chain must not have height less than
213 bool CheckAuto(const CBlockIndex *pindex)
217 if (pindex->IsInMainChain())
219 if (pindex->nHeight >= nAutoCheckpoint)
223 nBranchPoint = pindex->nHeight;
224 return error("Checkpoints: new block on alternative branch at height=%d before auto checkpoint at height=%d", pindex->nHeight, nAutoCheckpoint);
228 pindex = pindex->pprev;
230 return error("Checkpoints: failed to find any ancestor on main chain for the new block - internal error");
233 // ppcoin: get next chain checkpoint
234 int GetNextChainCheckpoint(const CBlockIndex *pindexLast)
237 CBigNum bnTargetMax = 0; // max target of all blocks since checkpoint
238 CBigNum bnTargetMin = 0; // min target of all candidate checkpoints
239 int nMinTargetHeight = 0; // min target height of candidate checkpoints
240 int nCheckpointMin = 0; // minimum candidate checkpoint
241 int nCheckpointMax = 0; // maximum candidate checkpoint
242 int nDepth = pindexLast->nHeight - pindexLast->nCheckpoint;
243 const CBlockIndex *pindex = pindexLast;
244 while (nDepth >= 0 && pindex)
246 bnTarget.SetCompact(pindex->nBits);
247 if (bnTarget > bnTargetMax)
248 bnTargetMax = bnTarget;
249 if (nCheckpointMax > 0 && bnTarget < bnTargetMin)
251 bnTargetMin = bnTarget;
252 nMinTargetHeight = pindex->nHeight;
254 if (nCheckpointMax == 0 && pindexLast->GetBlockTime() - pindex->GetBlockTime() > AUTO_CHECKPOINT_MIN_SPAN)
256 nCheckpointMax = pindex->nHeight;
257 bnTargetMin.SetCompact(pindex->nBits);
258 nMinTargetHeight = pindex->nHeight;
260 if (pindexLast->GetBlockTime() - pindex->GetBlockTime() < AUTO_CHECKPOINT_MAX_SPAN)
261 nCheckpointMin = pindex->nHeight;
262 pindex = pindex->pprev;
266 assert (nDepth == -1); // arrive at chain checkpoint now
268 printf("Checkpoints: min=%d max=%d tminheight=%d tmin=0x%08x tmax=0x%08x\n",
269 nCheckpointMin, nCheckpointMax, nMinTargetHeight,
270 bnTargetMin.GetCompact(), bnTargetMax.GetCompact());
271 if (nCheckpointMax == 0) // checkpoint stays if max candidate not found
272 return pindexLast->nCheckpoint;
274 if (bnTargetMin * 100 > bnTargetMax * 90)
275 return nCheckpointMax;
276 if (bnTarget * 100 > bnTargetMax * 90)
277 return nMinTargetHeight;
279 return nCheckpointMin;
282 // ppcoin: get next auto checkpoint from the new chain checkpoint
283 int GetNextAutoCheckpoint(int nCheckpoint)
285 return (std::max(nAutoCheckpoint, nCheckpoint));
288 // ppcoin: advance to next automatic checkpoint
289 void AdvanceAutoCheckpoint(int nCheckpoint)
291 nAutoCheckpoint = GetNextAutoCheckpoint(nCheckpoint);
292 printf("Checkpoints: auto checkpoint now at height=%d\n", nAutoCheckpoint);
295 // ppcoin: reset auto checkpoint
296 bool ResetAutoCheckpoint(int nCheckpoint)
298 if (nCheckpoint <= 0 || nCheckpoint > nBestHeight)
299 return error("ResetAutoCheckpoint() : new checkpoint invalid");
300 if (nCheckpoint >= nAutoCheckpoint)
301 return error("ResetAutoCheckpoint() : new checkpoint not earlier than current auto checkpoint");
304 if (!txdb.WriteAutoCheckpoint(nCheckpoint, true))
305 return error("ResetAutoCheckpoint() : database write failed");
306 if (!txdb.TxnCommit())
307 return error("ResetAutoCheckpoint() : database commit failed");
308 nAutoCheckpoint = nCheckpoint;
309 nBranchPoint = 0; // clear branch point
311 // clear ban list to accept alternative branches
312 CRITICAL_BLOCK(cs_vNodes)
314 BOOST_FOREACH(CNode* pnode, vNodes)
315 pnode->ClearBanned();
322 // ppcoin: process synchronized checkpoint
323 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
325 if (!CheckSignature())
328 CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)
330 if (!mapBlockIndex.count(hashCheckpoint))
332 // We haven't received the checkpoint chain, keep the checkpoint as pending
333 Checkpoints::checkpointMessagePending = *this;
334 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
335 // Ask this guy to fill in what we're missing
338 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
339 // ask directly as well in case rejected earlier by duplicate
340 // proof-of-stake because getblocks may not get it this time
341 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? GetOrphanRoot(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
346 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
350 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
351 if (!pindexCheckpoint->IsInMainChain())
353 // checkpoint chain received but not yet main chain
355 if (!Reorganize(txdb, pindexCheckpoint))
358 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
359 return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
364 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
367 return error("ProcessSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
369 if (!txdb.TxnCommit())
370 return error("ProcessSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
373 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
374 Checkpoints::checkpointMessage = *this;
375 Checkpoints::checkpointMessagePending.SetNull();
376 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());