PPCoin: Checkpoint master key as class constant
[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     bool IsPendingSyncCheckpoint(uint256 hashBlock)
199     {
200         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
201             return ((!checkpointMessagePending.IsNull()) && hashBlock == checkpointMessagePending.hashCheckpoint);
202     }
203
204     // ppcoin: automatic checkpoint (represented by height of checkpoint)
205     int nAutoCheckpoint = 0;
206     int nBranchPoint = 0;    // branch point to alternative branch
207
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
212     //     checkpoint height
213     bool CheckAuto(const CBlockIndex *pindex)
214     {
215         while (pindex)
216         {
217             if (pindex->IsInMainChain())
218             {
219                 if (pindex->nHeight >= nAutoCheckpoint)
220                     return true;
221                 else
222                 {
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);
225                 }
226             }
227             else
228                 pindex = pindex->pprev;
229         }
230         return error("Checkpoints: failed to find any ancestor on main chain for the new block - internal error");
231     }
232
233     // ppcoin: get next chain checkpoint
234     int GetNextChainCheckpoint(const CBlockIndex *pindexLast)
235     {
236         CBigNum bnTarget;
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)
245         {
246             bnTarget.SetCompact(pindex->nBits);
247             if (bnTarget > bnTargetMax)
248                 bnTargetMax = bnTarget;
249             if (nCheckpointMax > 0 && bnTarget < bnTargetMin)
250             {
251                 bnTargetMin = bnTarget;
252                 nMinTargetHeight = pindex->nHeight;
253             }
254             if (nCheckpointMax == 0 && pindexLast->GetBlockTime() - pindex->GetBlockTime() > AUTO_CHECKPOINT_MIN_SPAN)
255             {
256                 nCheckpointMax = pindex->nHeight;
257                 bnTargetMin.SetCompact(pindex->nBits);
258                 nMinTargetHeight = pindex->nHeight;
259             }
260             if (pindexLast->GetBlockTime() - pindex->GetBlockTime() < AUTO_CHECKPOINT_MAX_SPAN)
261                 nCheckpointMin = pindex->nHeight;
262             pindex = pindex->pprev;
263             nDepth--;
264         }
265
266         assert (nDepth == -1);  // arrive at chain checkpoint now
267
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;
273
274         if (bnTargetMin * 100 > bnTargetMax * 90)
275             return nCheckpointMax;
276         if (bnTarget * 100 > bnTargetMax * 90)
277             return nMinTargetHeight;
278         else
279             return nCheckpointMin;
280     }
281
282     // ppcoin: get next auto checkpoint from the new chain checkpoint
283     int GetNextAutoCheckpoint(int nCheckpoint)
284     {
285         return (std::max(nAutoCheckpoint, nCheckpoint));
286     }
287
288     // ppcoin: advance to next automatic checkpoint
289     void AdvanceAutoCheckpoint(int nCheckpoint)
290     {
291         nAutoCheckpoint = GetNextAutoCheckpoint(nCheckpoint);
292         printf("Checkpoints: auto checkpoint now at height=%d\n", nAutoCheckpoint);
293     }
294
295     // ppcoin: reset auto checkpoint
296     bool ResetAutoCheckpoint(int nCheckpoint)
297     {
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");
302         CTxDB txdb;
303         txdb.TxnBegin();
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
310
311         // clear ban list to accept alternative branches
312         CRITICAL_BLOCK(cs_vNodes)
313         {
314             BOOST_FOREACH(CNode* pnode, vNodes)
315                 pnode->ClearBanned();
316         }
317
318         return true;
319     }
320 }
321
322 // ppcoin: sync-checkpoint master key
323 const std::string CSyncCheckpoint::strMasterPubKey = "0424f20205e5da98ba632bbd278a11a6499585f62bfb2c782377ef59f0251daab8085fc31471bcb8180bc75ed0fa41bb50c7c084511d54015a3a5241d645c7268a";
324
325 // ppcoin: verify signature of sync-checkpoint message
326 bool CSyncCheckpoint::CheckSignature()
327 {
328     CKey key;
329     if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
330         return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
331     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
332         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
333
334     // Now unserialize the data
335     CDataStream sMsg(vchMsg);
336     sMsg >> *(CUnsignedSyncCheckpoint*)this;
337     return true;
338 }
339
340 // ppcoin: process synchronized checkpoint
341 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
342 {
343     if (!CheckSignature())
344         return false;
345
346     CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)
347     {
348         if (!mapBlockIndex.count(hashCheckpoint))
349         {
350             // We haven't received the checkpoint chain, keep the checkpoint as pending
351             Checkpoints::checkpointMessagePending = *this;
352             printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
353             // Ask this guy to fill in what we're missing
354             if (pfrom)
355             {
356                 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
357                 // ask directly as well in case rejected earlier by duplicate
358                 // proof-of-stake because getblocks may not get it this time
359                 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? GetOrphanRoot(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
360             }
361             return false;
362         }
363
364         if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
365             return false;
366
367         CTxDB txdb;
368         CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
369         if (!pindexCheckpoint->IsInMainChain())
370         {
371             // checkpoint chain received but not yet main chain
372             txdb.TxnBegin();
373             if (!Reorganize(txdb, pindexCheckpoint))
374             {
375                 txdb.TxnAbort();
376                 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
377                 return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
378             }
379         }
380
381         txdb.TxnBegin();
382         if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
383         {
384             txdb.TxnAbort();
385             return error("ProcessSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
386         }
387         if (!txdb.TxnCommit())
388             return error("ProcessSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
389         txdb.Close();
390
391         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
392         Checkpoints::checkpointMessage = *this;
393         Checkpoints::checkpointMessagePending.SetNull();
394         printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
395     }
396     return true;
397 }