PPCoin: Enter safe mode if detected invalid synchronized checkpoint
[novacoin.git] / src / checkpoints.cpp
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.
5
6 #include <boost/assign/list_of.hpp> // for 'map_list_of()'
7 #include <boost/foreach.hpp>
8
9 #include "headers.h"
10 #include "checkpoints.h"
11
12 namespace Checkpoints
13 {
14     typedef std::map<int, uint256> MapCheckpoints;   // hardened checkpoints
15
16     //
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
20     //    timestamp before)
21     // + Contains no strange transactions
22     //
23     static MapCheckpoints mapCheckpoints =
24         boost::assign::map_list_of
25         ( 0, hashGenesisBlock )
26         ; // ppcoin: no checkpoint yet; to be created in future releases
27
28     bool CheckHardened(int nHeight, const uint256& hash)
29     {
30         if (fTestNet) return true; // Testnet has no checkpoints
31
32         MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
33         if (i == mapCheckpoints.end()) return true;
34         return hash == i->second;
35     }
36
37     int GetTotalBlocksEstimate()
38     {
39         if (fTestNet) return 0;
40
41         return mapCheckpoints.rbegin()->first;
42     }
43
44     CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
45     {
46         if (fTestNet) return NULL;
47
48         int64 nResult;
49         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
50         {
51             const uint256& hash = i.second;
52             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
53             if (t != mapBlockIndex.end())
54                 return t->second;
55         }
56         return NULL;
57     }
58
59     // ppcoin: synchronized checkpoint (centrally broadcasted)
60     uint256 hashSyncCheckpoint;
61     CSyncCheckpoint checkpointMessage;
62     CSyncCheckpoint checkpointMessagePending;
63     uint256 hashInvalidCheckpoint = 0;
64     CCriticalSection cs_hashSyncCheckpoint;
65
66     // ppcoin: only descendant of current sync-checkpoint is allowed
67     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
68     {
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());
73
74         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
75         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
76
77         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
78         {
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)
87             {
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());
90             }
91             return false; // ignore older checkpoint
92         }
93
94         // Received checkpoint should be a descendant block of the current
95         // checkpoint. Trace back to the same height of current checkpoint
96         // to verify.
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)
102         {
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());
105         }
106         return true;
107     }
108
109     bool AcceptPendingSyncCheckpoint()
110     {
111         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
112         {
113             if ((!checkpointMessagePending.IsNull()) && mapBlockIndex.count(checkpointMessagePending.hashCheckpoint))
114             {
115                 if (!ValidateSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
116                 {
117                     checkpointMessagePending.SetNull();
118                     return false;
119                 }
120
121                 CTxDB txdb;
122                 CBlockIndex* pindexCheckpoint = mapBlockIndex[checkpointMessagePending.hashCheckpoint];
123                 if (!pindexCheckpoint->IsInMainChain())
124                 {
125                     txdb.TxnBegin();
126                     if (!Reorganize(txdb, pindexCheckpoint))
127                     {
128                         txdb.TxnAbort();
129                         hashInvalidCheckpoint = checkpointMessagePending.hashCheckpoint;
130                         return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", checkpointMessagePending.hashCheckpoint.ToString().c_str());
131                     }
132                 }
133
134                 txdb.TxnBegin();
135                 if (!txdb.WriteSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
136                 {
137                     txdb.TxnAbort();
138                     return error("AcceptPendingSyncCheckpoint() : failed to write to db sync checkpoint %s\n", checkpointMessagePending.hashCheckpoint.ToString().c_str());
139                 }
140                 if (!txdb.TxnCommit())
141                     return error("AcceptPendingSyncCheckpoint() : failed to commit to db sync checkpoint %s\n", checkpointMessagePending.hashCheckpoint.ToString().c_str());
142                 txdb.Close();
143
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);
152                 return true;
153             }
154         }
155
156         return false;
157     }
158
159     uint256 AutoSelectSyncCheckpoint()
160     {
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();
166     }
167
168     // Check against synchronized checkpoint
169     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
170     {
171         if (fTestNet) return true; // Testnet has no checkpoints
172         int nHeight = pindexPrev->nHeight + 1;
173
174         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
175         {
176             // sync-checkpoint should always be accepted block
177             assert(mapBlockIndex.count(hashSyncCheckpoint));
178             const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
179
180             if (nHeight > pindexSync->nHeight)
181             {
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
189             }
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
194         }
195         return true;
196     }
197
198     // ppcoin: automatic checkpoint (represented by height of checkpoint)
199     int nAutoCheckpoint = 0;
200     int nBranchPoint = 0;    // branch point to alternative branch
201
202     // ppcoin: check automatic checkpoint
203     // To pass the check:
204     //   - All ancestors (including the block itself) have block index already
205     //   - The immediate ancestor in main chain must not have height less than
206     //     checkpoint height
207     bool CheckAuto(const CBlockIndex *pindex)
208     {
209         while (pindex)
210         {
211             if (pindex->IsInMainChain())
212             {
213                 if (pindex->nHeight >= nAutoCheckpoint)
214                     return true;
215                 else
216                 {
217                     nBranchPoint = pindex->nHeight;
218                     return error("Checkpoints: new block on alternative branch at height=%d before auto checkpoint at height=%d", pindex->nHeight, nAutoCheckpoint);
219                 }
220             }
221             else
222                 pindex = pindex->pprev;
223         }
224         return error("Checkpoints: failed to find any ancestor on main chain for the new block - internal error");
225     }
226
227     // ppcoin: get next chain checkpoint
228     int GetNextChainCheckpoint(const CBlockIndex *pindexLast)
229     {
230         CBigNum bnTarget;
231         CBigNum bnTargetMax = 0;  // max target of all blocks since checkpoint
232         CBigNum bnTargetMin = 0;  // min target of all candidate checkpoints
233         int nMinTargetHeight = 0; // min target height of candidate checkpoints
234         int nCheckpointMin = 0;   // minimum candidate checkpoint
235         int nCheckpointMax = 0;   // maximum candidate checkpoint
236         int nDepth = pindexLast->nHeight - pindexLast->nCheckpoint;
237         const CBlockIndex *pindex = pindexLast;
238         while (nDepth >= 0 && pindex)
239         {
240             bnTarget.SetCompact(pindex->nBits);
241             if (bnTarget > bnTargetMax)
242                 bnTargetMax = bnTarget;
243             if (nCheckpointMax > 0 && bnTarget < bnTargetMin)
244             {
245                 bnTargetMin = bnTarget;
246                 nMinTargetHeight = pindex->nHeight;
247             }
248             if (nCheckpointMax == 0 && pindexLast->GetBlockTime() - pindex->GetBlockTime() > AUTO_CHECKPOINT_MIN_SPAN)
249             {
250                 nCheckpointMax = pindex->nHeight;
251                 bnTargetMin.SetCompact(pindex->nBits);
252                 nMinTargetHeight = pindex->nHeight;
253             }
254             if (pindexLast->GetBlockTime() - pindex->GetBlockTime() < AUTO_CHECKPOINT_MAX_SPAN)
255                 nCheckpointMin = pindex->nHeight;
256             pindex = pindex->pprev;
257             nDepth--;
258         }
259
260         assert (nDepth == -1);  // arrive at chain checkpoint now
261
262         printf("Checkpoints: min=%d max=%d tminheight=%d tmin=0x%08x tmax=0x%08x\n",
263             nCheckpointMin, nCheckpointMax, nMinTargetHeight,
264             bnTargetMin.GetCompact(), bnTargetMax.GetCompact());
265         if (nCheckpointMax == 0) // checkpoint stays if max candidate not found
266             return pindexLast->nCheckpoint;
267
268         if (bnTargetMin * 100 > bnTargetMax * 90)
269             return nCheckpointMax;
270         if (bnTarget * 100 > bnTargetMax * 90)
271             return nMinTargetHeight;
272         else
273             return nCheckpointMin;
274     }
275
276     // ppcoin: get next auto checkpoint from the new chain checkpoint
277     int GetNextAutoCheckpoint(int nCheckpoint)
278     {
279         return (std::max(nAutoCheckpoint, nCheckpoint));
280     }
281
282     // ppcoin: advance to next automatic checkpoint
283     void AdvanceAutoCheckpoint(int nCheckpoint)
284     {
285         nAutoCheckpoint = GetNextAutoCheckpoint(nCheckpoint);
286         printf("Checkpoints: auto checkpoint now at height=%d\n", nAutoCheckpoint);
287     }
288
289     // ppcoin: reset auto checkpoint
290     bool ResetAutoCheckpoint(int nCheckpoint)
291     {
292         if (nCheckpoint <= 0 || nCheckpoint > nBestHeight)
293             return error("ResetAutoCheckpoint() : new checkpoint invalid");
294         if (nCheckpoint >= nAutoCheckpoint)
295             return error("ResetAutoCheckpoint() : new checkpoint not earlier than current auto checkpoint");
296         CTxDB txdb;
297         txdb.TxnBegin();
298         if (!txdb.WriteAutoCheckpoint(nCheckpoint, true))
299             return error("ResetAutoCheckpoint() : database write failed");
300         if (!txdb.TxnCommit())
301             return error("ResetAutoCheckpoint() : database commit failed");
302         nAutoCheckpoint = nCheckpoint;
303         nBranchPoint = 0;  // clear branch point
304
305         // clear ban list to accept alternative branches
306         CRITICAL_BLOCK(cs_vNodes)
307         {
308             BOOST_FOREACH(CNode* pnode, vNodes)
309                 pnode->ClearBanned();
310         }
311
312         return true;
313     }
314 }
315
316 // ppcoin: process synchronized checkpoint
317 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
318 {
319     if (!CheckSignature())
320         return false;
321
322     CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)
323     {
324         if (!mapBlockIndex.count(hashCheckpoint))
325         {
326             // We haven't received the checkpoint chain, keep the checkpoint as pending
327             Checkpoints::checkpointMessagePending = *this;
328             printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
329             // Ask this guy to fill in what we're missing
330             if (pfrom)
331                 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
332             return false;
333         }
334
335         if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
336             return false;
337
338         CTxDB txdb;
339         CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
340         if (!pindexCheckpoint->IsInMainChain())
341         {
342             // checkpoint chain received but not yet main chain
343             txdb.TxnBegin();
344             if (!Reorganize(txdb, pindexCheckpoint))
345             {
346                 txdb.TxnAbort();
347                 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
348                 return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
349             }
350         }
351
352         txdb.TxnBegin();
353         if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
354         {
355             txdb.TxnAbort();
356             return error("ProcessSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
357         }
358         if (!txdb.TxnCommit())
359             return error("ProcessSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
360         txdb.Close();
361
362         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
363         Checkpoints::checkpointMessage = *this;
364         Checkpoints::checkpointMessagePending.SetNull();
365         printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
366     }
367     return true;
368 }