PPCoin: Force reorganization for 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     CCriticalSection cs_hashSyncCheckpoint;
64
65     // ppcoin: only descendant of current sync-checkpoint is allowed
66     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
67     {
68         if (!mapBlockIndex.count(hashSyncCheckpoint))
69             return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
70         if (!mapBlockIndex.count(hashCheckpoint))
71             return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
72
73         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
74         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
75         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
76             return false;  // this is an older checkpoint, ignore
77
78         CBlockIndex* pindex = pindexCheckpointRecv;
79         while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
80             if (!(pindex = pindex->pprev))
81                 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
82         if (pindex->GetBlockHash() != hashSyncCheckpoint)
83             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
84         return true;
85     }
86
87     bool AcceptPendingSyncCheckpoint()
88     {
89         bool fAccepted = false;
90         uint256 hashCheckpoint = 0;
91         CTxDB txdb;
92
93         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
94         {
95             if ((!checkpointMessagePending.IsNull()) && mapBlockIndex.count(checkpointMessagePending.hashCheckpoint))
96             {
97                 if (!ValidateSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
98                 {
99                     checkpointMessagePending.SetNull();
100                     return false;
101                 }
102
103                 txdb.TxnBegin();
104                 if (!txdb.WriteSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
105                 {
106                     txdb.TxnAbort();
107                     return error("AcceptPendingSyncCheckpoint() : failed to write to db sync checkpoint %s\n", checkpointMessagePending.hashCheckpoint.ToString().c_str());
108                 }
109                 if (!txdb.TxnCommit())
110                     return error("AcceptPendingSyncCheckpoint() : failed to commit to db sync checkpoint %s\n", checkpointMessagePending.hashCheckpoint.ToString().c_str());
111
112                 hashSyncCheckpoint = checkpointMessagePending.hashCheckpoint;
113                 checkpointMessage = checkpointMessagePending;
114                 checkpointMessagePending.SetNull();
115                 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
116                 fAccepted = true;
117                 hashCheckpoint = hashSyncCheckpoint;
118             }
119         }
120
121         if (fAccepted)
122         {
123             CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
124             if (!pindexCheckpoint->IsInMainChain())
125             {
126                 txdb.TxnBegin();
127                 if (!Reorganize(txdb, pindexCheckpoint))
128                 {
129                     txdb.TxnAbort();
130                     return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
131                 }
132             }
133         }
134         txdb.Close();
135
136         // relay the checkpoint
137         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
138             BOOST_FOREACH(CNode* pnode, vNodes)
139                 checkpointMessage.RelayTo(pnode);
140
141         return fAccepted;
142     }
143
144     uint256 AutoSelectSyncCheckpoint()
145     {
146         // select block roughly 8 hours ago
147         CBlockIndex *pindex = mapBlockIndex[hashSyncCheckpoint];
148         while (pindex->pnext && pindex->pnext->GetBlockTime() + AUTO_CHECKPOINT_MIN_SPAN <= GetAdjustedTime())
149             pindex = pindex->pnext;
150         return pindex->GetBlockHash();
151     }
152
153     // Check against synchronized checkpoint
154     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
155     {
156         if (fTestNet) return true; // Testnet has no checkpoints
157         int nHeight = pindexPrev->nHeight + 1;
158
159         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
160         {
161             // sync-checkpoint should always be accepted block
162             assert(mapBlockIndex.count(hashSyncCheckpoint));
163             const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
164
165             if (nHeight > pindexSync->nHeight)
166             {
167                 // trace back to same height as sync-checkpoint
168                 const CBlockIndex* pindex = pindexPrev;
169                 while (pindex->nHeight > pindexSync->nHeight)
170                     if (!(pindex = pindex->pprev))
171                         return error("CheckSync: pprev null - block index structure failure");
172                 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
173                     return false; // only descendant of sync-checkpoint can pass check
174             }
175             if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
176                 return false; // same height with sync-checkpoint
177             if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
178                 return false; // lower height than sync-checkpoint
179         }
180         return true;
181     }
182
183     // ppcoin: automatic checkpoint (represented by height of checkpoint)
184     int nAutoCheckpoint = 0;
185     int nBranchPoint = 0;    // branch point to alternative branch
186
187     // ppcoin: check automatic checkpoint
188     // To pass the check:
189     //   - All ancestors (including the block itself) have block index already
190     //   - The immediate ancestor in main chain must not have height less than
191     //     checkpoint height
192     bool CheckAuto(const CBlockIndex *pindex)
193     {
194         while (pindex)
195         {
196             if (pindex->IsInMainChain())
197             {
198                 if (pindex->nHeight >= nAutoCheckpoint)
199                     return true;
200                 else
201                 {
202                     nBranchPoint = pindex->nHeight;
203                     return error("Checkpoints: new block on alternative branch at height=%d before auto checkpoint at height=%d", pindex->nHeight, nAutoCheckpoint);
204                 }
205             }
206             else
207                 pindex = pindex->pprev;
208         }
209         return error("Checkpoints: failed to find any ancestor on main chain for the new block - internal error");
210     }
211
212     // ppcoin: get next chain checkpoint
213     int GetNextChainCheckpoint(const CBlockIndex *pindexLast)
214     {
215         CBigNum bnTarget;
216         CBigNum bnTargetMax = 0;  // max target of all blocks since checkpoint
217         CBigNum bnTargetMin = 0;  // min target of all candidate checkpoints
218         int nMinTargetHeight = 0; // min target height of candidate checkpoints
219         int nCheckpointMin = 0;   // minimum candidate checkpoint
220         int nCheckpointMax = 0;   // maximum candidate checkpoint
221         int nDepth = pindexLast->nHeight - pindexLast->nCheckpoint;
222         const CBlockIndex *pindex = pindexLast;
223         while (nDepth >= 0 && pindex)
224         {
225             bnTarget.SetCompact(pindex->nBits);
226             if (bnTarget > bnTargetMax)
227                 bnTargetMax = bnTarget;
228             if (nCheckpointMax > 0 && bnTarget < bnTargetMin)
229             {
230                 bnTargetMin = bnTarget;
231                 nMinTargetHeight = pindex->nHeight;
232             }
233             if (nCheckpointMax == 0 && pindexLast->GetBlockTime() - pindex->GetBlockTime() > AUTO_CHECKPOINT_MIN_SPAN)
234             {
235                 nCheckpointMax = pindex->nHeight;
236                 bnTargetMin.SetCompact(pindex->nBits);
237                 nMinTargetHeight = pindex->nHeight;
238             }
239             if (pindexLast->GetBlockTime() - pindex->GetBlockTime() < AUTO_CHECKPOINT_MAX_SPAN)
240                 nCheckpointMin = pindex->nHeight;
241             pindex = pindex->pprev;
242             nDepth--;
243         }
244
245         assert (nDepth == -1);  // arrive at chain checkpoint now
246
247         printf("Checkpoints: min=%d max=%d tminheight=%d tmin=0x%08x tmax=0x%08x\n",
248             nCheckpointMin, nCheckpointMax, nMinTargetHeight,
249             bnTargetMin.GetCompact(), bnTargetMax.GetCompact());
250         if (nCheckpointMax == 0) // checkpoint stays if max candidate not found
251             return pindexLast->nCheckpoint;
252
253         if (bnTargetMin * 100 > bnTargetMax * 90)
254             return nCheckpointMax;
255         if (bnTarget * 100 > bnTargetMax * 90)
256             return nMinTargetHeight;
257         else
258             return nCheckpointMin;
259     }
260
261     // ppcoin: get next auto checkpoint from the new chain checkpoint
262     int GetNextAutoCheckpoint(int nCheckpoint)
263     {
264         return (std::max(nAutoCheckpoint, nCheckpoint));
265     }
266
267     // ppcoin: advance to next automatic checkpoint
268     void AdvanceAutoCheckpoint(int nCheckpoint)
269     {
270         nAutoCheckpoint = GetNextAutoCheckpoint(nCheckpoint);
271         printf("Checkpoints: auto checkpoint now at height=%d\n", nAutoCheckpoint);
272     }
273
274     // ppcoin: reset auto checkpoint
275     bool ResetAutoCheckpoint(int nCheckpoint)
276     {
277         if (nCheckpoint <= 0 || nCheckpoint > nBestHeight)
278             return error("ResetAutoCheckpoint() : new checkpoint invalid");
279         if (nCheckpoint >= nAutoCheckpoint)
280             return error("ResetAutoCheckpoint() : new checkpoint not earlier than current auto checkpoint");
281         CTxDB txdb;
282         txdb.TxnBegin();
283         if (!txdb.WriteAutoCheckpoint(nCheckpoint, true))
284             return error("ResetAutoCheckpoint() : database write failed");
285         if (!txdb.TxnCommit())
286             return error("ResetAutoCheckpoint() : database commit failed");
287         nAutoCheckpoint = nCheckpoint;
288         nBranchPoint = 0;  // clear branch point
289
290         // clear ban list to accept alternative branches
291         CRITICAL_BLOCK(cs_vNodes)
292         {
293             BOOST_FOREACH(CNode* pnode, vNodes)
294                 pnode->ClearBanned();
295         }
296
297         return true;
298     }
299 }
300
301 // ppcoin: process synchronized checkpoint
302 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
303 {
304     if (!CheckSignature())
305         return false;
306
307     CTxDB txdb;
308     CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)
309     {
310         if (!mapBlockIndex.count(hashCheckpoint))
311         {
312             // We haven't accepted this block, keep the checkpoint as pending
313             Checkpoints::checkpointMessagePending = *this;
314             printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
315             // Ask this guy to fill in what we're missing
316             if (pfrom)
317                 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
318             return false;
319         }
320         if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
321             return false;
322
323         txdb.TxnBegin();
324         if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
325         {
326             txdb.TxnAbort();
327             return error("ProcessSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
328         }
329         if (!txdb.TxnCommit())
330             return error("ProcessSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
331
332         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
333         Checkpoints::checkpointMessage = *this;
334         Checkpoints::checkpointMessagePending.SetNull();
335         printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
336     }
337
338     CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
339     if (!pindexCheckpoint->IsInMainChain())
340     {
341         txdb.TxnBegin();
342         if (!Reorganize(txdb, pindexCheckpoint))
343         {
344             txdb.TxnAbort();
345             return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
346         }
347     }
348     txdb.Close();
349     return true;
350 }