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