Add checkpoint @ block # 532000
[novacoin.git] / src / checkpoints.cpp
1 // Copyright (c) 2009-2012 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include <boost/assign/list_of.hpp> // for 'map_list_of()'
6 #include <boost/foreach.hpp>
7 #include <algorithm>
8
9 #include "checkpoints.h"
10
11 #include "txdb.h"
12 #include "main.h"
13 #include "uint256.h"
14
15 namespace Checkpoints
16 {
17     typedef std::map<int, std::pair<uint256, unsigned int> > MapCheckpoints;
18     typedef std::list<uint256> ListBannedBlocks;
19
20     //
21     // What makes a good checkpoint block?
22     // + Is surrounded by blocks with reasonable timestamps
23     //   (no blocks before with a timestamp after, none after with
24     //    timestamp before)
25     // + Contains no strange transactions
26     //
27     static MapCheckpoints mapCheckpoints =
28         boost::assign::map_list_of
29         ( 0,      std::make_pair(hashGenesisBlock, 1360105017) )
30         ( 13560,  std::make_pair(uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052) )
31         ( 143990, std::make_pair(uint256("0x00000000001ff5c3940a9f73ad4a990f64955179bde0f743c76dbf0031429efc"), 1418953493) )
32         ( 149000, std::make_pair(uint256("0x7a24acfcadcf43054e7f7d9f273522c0dfc5791ba4006e0273e7521a8d36c525"), 1420872125) )
33         ( 160000, std::make_pair(uint256("0x000000000001cb1133043d38d077c0e93f66c8b2566779f10f182137d1e34a68"), 1425150237) )
34         ( 200000, std::make_pair(uint256("0x0000000000029f8bbf66e6ea6f3e5db55009404aae0fe395a53dd33142b2bff2"), 1441127233) )
35         ( 221047, std::make_pair(uint256("0xa28aef712e7aa0c285bfe29351ca21ed416689139e3063ef770fc826a8b9e9da"), 1449431646) )
36         ( 243100, std::make_pair(uint256("0x000000000006522d1ebc0734cb0e6b83f5d4da0c3cbc72bd91b82016f611c4f0"), 1458215793) )
37         ( 532000, std::make_pair(uint256("0x0000000000018b7eba5e189c41605780c8a855f74144fa837fa05fa4c67b6ba9"), 1569359486) )
38     ;
39
40     static ListBannedBlocks listBanned =
41         boost::assign::list_of
42         // Invalid block #221047 with future timestamp of 2016/02/23 09:24:17 UTC
43         ( uint256("0x46223e5432ceffe650d5729b4bb8479dcdf0ca1e534fa8e69382dc87b42ea94b") )
44     ;
45
46     // TestNet has no checkpoints
47     static MapCheckpoints mapCheckpointsTestnet =
48         boost::assign::map_list_of
49         ( 0, std::make_pair(hashGenesisBlockTestNet, 1360105017) )
50         ;
51
52     bool CheckHardened(int nHeight, const uint256& hash)
53     {
54         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
55
56         MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
57         if (i == checkpoints.end()) return true;
58         return hash == i->second.first;
59     }
60
61     bool CheckBanned(const uint256 &nHash)
62     {
63         if (fTestNet) // Testnet has no banned blocks
64             return true;
65         ListBannedBlocks::const_iterator it = std::find(listBanned.begin(), listBanned.end(), nHash);
66         return it == listBanned.end();
67     }
68
69     int GetTotalBlocksEstimate()
70     {
71         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
72
73         return checkpoints.rbegin()->first;
74     }
75
76     unsigned int GetLastCheckpointTime()
77     {
78         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
79
80         return checkpoints.rbegin()->second.second;
81     }
82
83     CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
84     {
85         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
86
87         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
88         {
89             const uint256& hash = i.second.first;
90             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
91             if (t != mapBlockIndex.end())
92                 return t->second;
93         }
94         return NULL;
95     }
96
97     // ppcoin: synchronized checkpoint (centrally broadcasted)
98     uint256 hashSyncCheckpoint = 0;
99     uint256 hashPendingCheckpoint = 0;
100     CSyncCheckpoint checkpointMessage;
101     CSyncCheckpoint checkpointMessagePending;
102     uint256 hashInvalidCheckpoint = 0;
103     CCriticalSection cs_hashSyncCheckpoint;
104
105     // ppcoin: get last synchronized checkpoint
106     CBlockIndex* GetLastSyncCheckpoint()
107     {
108         LOCK(cs_hashSyncCheckpoint);
109         if (!mapBlockIndex.count(hashSyncCheckpoint))
110             error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
111         else
112             return mapBlockIndex[hashSyncCheckpoint];
113         return NULL;
114     }
115
116     // ppcoin: only descendant of current sync-checkpoint is allowed
117     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
118     {
119         if (!mapBlockIndex.count(hashSyncCheckpoint))
120             return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
121         if (!mapBlockIndex.count(hashCheckpoint))
122             return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
123
124         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
125         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
126
127         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
128         {
129             // Received an older checkpoint, trace back from current checkpoint
130             // to the same height of the received checkpoint to verify
131             // that current checkpoint should be a descendant block
132             CBlockIndex* pindex = pindexSyncCheckpoint;
133             while (pindex->nHeight > pindexCheckpointRecv->nHeight)
134                 if ((pindex = pindex->pprev) == NULL)
135                     return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
136             if (pindex->GetBlockHash() != hashCheckpoint)
137             {
138                 hashInvalidCheckpoint = hashCheckpoint;
139                 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
140             }
141             return false; // ignore older checkpoint
142         }
143
144         // Received checkpoint should be a descendant block of the current
145         // checkpoint. Trace back to the same height of current checkpoint
146         // to verify.
147         CBlockIndex* pindex = pindexCheckpointRecv;
148         while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
149             if ((pindex = pindex->pprev) == NULL)
150                 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
151         if (pindex->GetBlockHash() != hashSyncCheckpoint)
152         {
153             hashInvalidCheckpoint = hashCheckpoint;
154             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
155         }
156         return true;
157     }
158
159     bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
160     {
161         CTxDB txdb;
162         txdb.TxnBegin();
163         if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
164         {
165             txdb.TxnAbort();
166             return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
167         }
168         if (!txdb.TxnCommit())
169             return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
170
171 #ifndef USE_LEVELDB
172         txdb.Close();
173 #endif
174
175         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
176         return true;
177     }
178
179     bool AcceptPendingSyncCheckpoint()
180     {
181         LOCK(cs_hashSyncCheckpoint);
182         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
183         {
184             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
185             {
186                 hashPendingCheckpoint = 0;
187                 checkpointMessagePending.SetNull();
188                 return false;
189             }
190
191             CTxDB txdb;
192             CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
193             if (!pindexCheckpoint->IsInMainChain())
194             {
195                 CBlock block;
196                 if (!block.ReadFromDisk(pindexCheckpoint))
197                     return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
198                 if (!block.SetBestChain(txdb, pindexCheckpoint))
199                 {
200                     hashInvalidCheckpoint = hashPendingCheckpoint;
201                     return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
202                 }
203             }
204
205 #ifndef USE_LEVELDB
206             txdb.Close();
207 #endif
208             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
209                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
210             hashPendingCheckpoint = 0;
211             checkpointMessage = checkpointMessagePending;
212             checkpointMessagePending.SetNull();
213             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
214             // relay the checkpoint
215             if (!checkpointMessage.IsNull())
216             {
217                 for (std::vector<CNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it)
218                     checkpointMessage.RelayTo(*it);
219             }
220             return true;
221         }
222         return false;
223     }
224
225     // Automatically select a suitable sync-checkpoint 
226     uint256 AutoSelectSyncCheckpoint()
227     {
228         const CBlockIndex *pindex = pindexBest;
229         // Search backward for a block within max span and maturity window
230         while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
231             pindex = pindex->pprev;
232         return pindex->GetBlockHash();
233     }
234
235     // Check against synchronized checkpoint
236     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
237     {
238         if (fTestNet) return true; // Testnet has no checkpoints
239         int nHeight = pindexPrev->nHeight + 1;
240
241         LOCK(cs_hashSyncCheckpoint);
242         // sync-checkpoint should always be accepted block
243         assert(mapBlockIndex.count(hashSyncCheckpoint));
244         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
245
246         if (nHeight > pindexSync->nHeight)
247         {
248             // trace back to same height as sync-checkpoint
249             const CBlockIndex* pindex = pindexPrev;
250             while (pindex->nHeight > pindexSync->nHeight)
251                 if ((pindex = pindex->pprev) == NULL)
252                     return error("CheckSync: pprev null - block index structure failure");
253             if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
254                 return false; // only descendant of sync-checkpoint can pass check
255         }
256         if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
257             return false; // same height with sync-checkpoint
258         if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
259             return false; // lower height than sync-checkpoint
260         return true;
261     }
262
263     bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
264     {
265         LOCK(cs_hashSyncCheckpoint);
266         if (hashPendingCheckpoint == 0)
267             return false;
268         if (hashBlock == hashPendingCheckpoint)
269             return true;
270         if (mapOrphanBlocks.count(hashPendingCheckpoint) 
271             && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
272             return true;
273         return false;
274     }
275
276     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
277     bool ResetSyncCheckpoint()
278     {
279         LOCK(cs_hashSyncCheckpoint);
280         const uint256& hash = mapCheckpoints.rbegin()->second.first;
281         if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
282         {
283             // checkpoint block accepted but not yet in main chain
284             printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
285             CTxDB txdb;
286             CBlock block;
287             if (!block.ReadFromDisk(mapBlockIndex[hash]))
288                 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
289             if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
290             {
291                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
292             }
293
294 #ifndef USE_LEVELDB
295             txdb.Close();
296 #endif
297
298         }
299         else if(!mapBlockIndex.count(hash))
300         {
301             // checkpoint block not yet accepted
302             hashPendingCheckpoint = hash;
303             checkpointMessagePending.SetNull();
304             printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
305         }
306
307         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
308         {
309             const uint256& hash = i.second.first;
310             if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
311             {
312                 if (!WriteSyncCheckpoint(hash))
313                     return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
314                 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
315                 return true;
316             }
317         }
318
319         return false;
320     }
321
322     void AskForPendingSyncCheckpoint(CNode* pfrom)
323     {
324         LOCK(cs_hashSyncCheckpoint);
325         if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
326             pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
327     }
328
329     bool SetCheckpointPrivKey(std::string strPrivKey)
330     {
331         // Test signing a sync-checkpoint with genesis block
332         CSyncCheckpoint checkpoint;
333         checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
334         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
335         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
336         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
337
338         std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
339         CKey key;
340         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
341         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
342             return false;
343
344         // Test signing successful, proceed
345         CSyncCheckpoint::strMasterPrivKey = strPrivKey;
346         return true;
347     }
348
349     bool SendSyncCheckpoint(uint256 hashCheckpoint)
350     {
351         CSyncCheckpoint checkpoint;
352         checkpoint.hashCheckpoint = hashCheckpoint;
353         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
354         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
355         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
356
357         if (CSyncCheckpoint::strMasterPrivKey.empty())
358             return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
359         std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
360         CKey key;
361         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
362         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
363             return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
364
365         if(!checkpoint.ProcessSyncCheckpoint(NULL))
366         {
367             printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
368             return false;
369         }
370
371         // Relay checkpoint
372         {
373             LOCK(cs_vNodes);
374             for (std::vector<CNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it)
375                 checkpoint.RelayTo(*it);
376         }
377         return true;
378     }
379
380     // Is the sync-checkpoint outside maturity window?
381     bool IsMatureSyncCheckpoint()
382     {
383         LOCK(cs_hashSyncCheckpoint);
384         // sync-checkpoint should always be accepted block
385         assert(mapBlockIndex.count(hashSyncCheckpoint));
386         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
387         return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
388                 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
389     }
390 }
391
392 // ppcoin: sync-checkpoint master key
393 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
394
395 std::string CSyncCheckpoint::strMasterPrivKey = "";
396
397 // ppcoin: verify signature of sync-checkpoint message
398 bool CSyncCheckpoint::CheckSignature()
399 {
400     CPubKey key(ParseHex(CSyncCheckpoint::strMasterPubKey));
401     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
402         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
403
404     // Now unserialize the data
405     CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
406     sMsg >> *(CUnsignedSyncCheckpoint*)this;
407     return true;
408 }
409
410 // process synchronized checkpoint
411 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
412 {
413     if (!CheckSignature())
414         return false;
415
416     LOCK(Checkpoints::cs_hashSyncCheckpoint);
417     if (!mapBlockIndex.count(hashCheckpoint))
418     {
419         // We haven't received the checkpoint chain, keep the checkpoint as pending
420         Checkpoints::hashPendingCheckpoint = hashCheckpoint;
421         Checkpoints::checkpointMessagePending = *this;
422         printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
423         // Ask this guy to fill in what we're missing
424         if (pfrom)
425         {
426             pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
427             // ask directly as well in case rejected earlier by duplicate
428             // proof-of-stake because getblocks may not get it this time
429             pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
430         }
431         return false;
432     }
433
434     if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
435         return false;
436
437     CTxDB txdb;
438     CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
439     if (!pindexCheckpoint->IsInMainChain())
440     {
441         // checkpoint chain received but not yet main chain
442         CBlock block;
443         if (!block.ReadFromDisk(pindexCheckpoint))
444             return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
445         if (!block.SetBestChain(txdb, pindexCheckpoint))
446         {
447             Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
448             return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
449         }
450     }
451
452 #ifndef USE_LEVELDB
453     txdb.Close();
454 #endif
455
456     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
457         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
458     Checkpoints::checkpointMessage = *this;
459     Checkpoints::hashPendingCheckpoint = 0;
460     Checkpoints::checkpointMessagePending.SetNull();
461     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
462     return true;
463 }