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