Reorganize includes a bit
[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 <algorithm>
6
7 #include "checkpoints.h"
8
9 #include "txdb.h"
10 #include "main.h"
11 #include "uint256.h"
12
13 using namespace std;
14
15 extern unsigned int nStakeMinAge;
16
17 namespace Checkpoints
18 {
19     typedef map<int, pair<uint256, unsigned int> > MapCheckpoints;
20     typedef list<uint256> ListBannedBlocks;
21
22     //
23     // What makes a good checkpoint block?
24     // + Is surrounded by blocks with reasonable timestamps
25     //   (no blocks before with a timestamp after, none after with
26     //    timestamp before)
27     // + Contains no strange transactions
28     //
29     static MapCheckpoints mapCheckpoints =
30     {
31         { 0,      { hashGenesisBlock, 1360105017 } },
32         { 13560,  { uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052 } },
33         { 143990, { uint256("0x00000000001ff5c3940a9f73ad4a990f64955179bde0f743c76dbf0031429efc"), 1418953493 } },
34         { 149000, { uint256("0x7a24acfcadcf43054e7f7d9f273522c0dfc5791ba4006e0273e7521a8d36c525"), 1420872125 } },
35         { 160000, { uint256("0x000000000001cb1133043d38d077c0e93f66c8b2566779f10f182137d1e34a68"), 1425150237 } },
36         { 200000, { uint256("0x0000000000029f8bbf66e6ea6f3e5db55009404aae0fe395a53dd33142b2bff2"), 1441127233 } },
37         { 221047, { uint256("0xa28aef712e7aa0c285bfe29351ca21ed416689139e3063ef770fc826a8b9e9da"), 1449431646 } },
38         { 243100, { uint256("0x000000000006522d1ebc0734cb0e6b83f5d4da0c3cbc72bd91b82016f611c4f0"), 1458215793 } },
39     };
40
41     static ListBannedBlocks listBanned =
42     {
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     {
50         { 0, { hashGenesisBlockTestNet, 1360105017 } }
51     };
52
53     bool CheckHardened(int nHeight, const uint256& hash)
54     {
55         auto& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
56
57         auto 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         auto it = find(listBanned.begin(), listBanned.end(), nHash);
67         return it == listBanned.end();
68     }
69
70     int GetTotalBlocksEstimate()
71     {
72         auto& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
73
74         return checkpoints.rbegin()->first;
75     }
76
77     unsigned int GetLastCheckpointTime()
78     {
79         auto& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
80
81         return checkpoints.rbegin()->second.second;
82     }
83
84     CBlockIndex* GetLastCheckpoint(const map<uint256, CBlockIndex*>& mapBlockIndex)
85     {
86         auto& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
87
88         for(auto it = checkpoints.rbegin(); it != checkpoints.rend(); ++it)
89         {
90             auto& 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(const 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         auto pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
126         auto 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             auto 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         auto 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 #ifndef USE_LEVELDB
173         txdb.Close();
174 #endif
175
176         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
177         return true;
178     }
179
180     bool AcceptPendingSyncCheckpoint()
181     {
182         LOCK(cs_hashSyncCheckpoint);
183         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
184         {
185             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
186             {
187                 hashPendingCheckpoint = 0;
188                 checkpointMessagePending.SetNull();
189                 return false;
190             }
191
192             CTxDB txdb;
193             auto pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
194             if (!pindexCheckpoint->IsInMainChain())
195             {
196                 CBlock block;
197                 if (!block.ReadFromDisk(pindexCheckpoint))
198                     return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
199                 if (!block.SetBestChain(txdb, pindexCheckpoint))
200                 {
201                     hashInvalidCheckpoint = hashPendingCheckpoint;
202                     return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
203                 }
204             }
205
206 #ifndef USE_LEVELDB
207             txdb.Close();
208 #endif
209             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
210                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
211             hashPendingCheckpoint = 0;
212             checkpointMessage = checkpointMessagePending;
213             checkpointMessagePending.SetNull();
214             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
215             // relay the checkpoint
216             if (!checkpointMessage.IsNull())
217             {
218                 for (auto it = vNodes.begin(); it != vNodes.end(); ++it)
219                     checkpointMessage.RelayTo(*it);
220             }
221             return true;
222         }
223         return false;
224     }
225
226     // Automatically select a suitable sync-checkpoint 
227     uint256 AutoSelectSyncCheckpoint()
228     {
229         auto pindex = pindexBest;
230         // Search backward for a block within max span and maturity window
231         while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
232             pindex = pindex->pprev;
233         return pindex->GetBlockHash();
234     }
235
236     // Check against synchronized checkpoint
237     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
238     {
239         if (fTestNet) return true; // Testnet has no checkpoints
240         int nHeight = pindexPrev->nHeight + 1;
241
242         LOCK(cs_hashSyncCheckpoint);
243         // sync-checkpoint should always be accepted block
244         assert(mapBlockIndex.count(hashSyncCheckpoint));
245         auto pindexSync = mapBlockIndex[hashSyncCheckpoint];
246
247         if (nHeight > pindexSync->nHeight)
248         {
249             // trace back to same height as sync-checkpoint
250             auto pindex = pindexPrev;
251             while (pindex->nHeight > pindexSync->nHeight)
252                 if ((pindex = pindex->pprev) == NULL)
253                     return error("CheckSync: pprev null - block index structure failure");
254             if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
255                 return false; // only descendant of sync-checkpoint can pass check
256         }
257         if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
258             return false; // same height with sync-checkpoint
259         if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
260             return false; // lower height than sync-checkpoint
261         return true;
262     }
263
264     bool WantedByPendingSyncCheckpoint(const uint256 &hashBlock)
265     {
266         LOCK(cs_hashSyncCheckpoint);
267         if (hashPendingCheckpoint == 0)
268             return false;
269         if (hashBlock == hashPendingCheckpoint)
270             return true;
271         if (mapOrphanBlocks.count(hashPendingCheckpoint) 
272             && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
273             return true;
274         return false;
275     }
276
277     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
278     bool ResetSyncCheckpoint()
279     {
280         LOCK(cs_hashSyncCheckpoint);
281         const auto& hash = mapCheckpoints.rbegin()->second.first;
282         if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
283         {
284             // checkpoint block accepted but not yet in main chain
285             printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
286             CTxDB txdb;
287             CBlock block;
288             if (!block.ReadFromDisk(mapBlockIndex[hash]))
289                 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
290             if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
291             {
292                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
293             }
294
295 #ifndef USE_LEVELDB
296             txdb.Close();
297 #endif
298
299         }
300         else if(!mapBlockIndex.count(hash))
301         {
302             // checkpoint block not yet accepted
303             hashPendingCheckpoint = hash;
304             checkpointMessagePending.SetNull();
305             printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
306         }
307
308         for(auto it = mapCheckpoints.rbegin(); it != mapCheckpoints.rend(); ++it)
309         {
310             const auto& hash = it->second.first;
311             if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
312             {
313                 if (!WriteSyncCheckpoint(hash))
314                     return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
315                 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
316                 return true;
317             }
318         }
319
320         return false;
321     }
322
323     void AskForPendingSyncCheckpoint(CNode* pfrom)
324     {
325         LOCK(cs_hashSyncCheckpoint);
326         if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
327             pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
328     }
329
330     bool SetCheckpointPrivKey(const string &strPrivKey)
331     {
332         // Test signing a sync-checkpoint with genesis block
333         CSyncCheckpoint checkpoint;
334         checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
335         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
336         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
337         checkpoint.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
338
339         auto vchPrivKey = ParseHex(strPrivKey);
340         CKey key;
341         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
342         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
343             return false;
344
345         // Test signing successful, proceed
346         CSyncCheckpoint::strMasterPrivKey = strPrivKey;
347         return true;
348     }
349
350     bool SendSyncCheckpoint(const uint256 &hashCheckpoint)
351     {
352         CSyncCheckpoint checkpoint;
353         checkpoint.hashCheckpoint = hashCheckpoint;
354         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
355         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
356         checkpoint.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
357
358         if (CSyncCheckpoint::strMasterPrivKey.empty())
359             return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
360         auto vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
361         CKey key;
362         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
363         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
364             return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
365
366         if(!checkpoint.ProcessSyncCheckpoint(NULL))
367         {
368             printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
369             return false;
370         }
371
372         // Relay checkpoint
373         {
374             LOCK(cs_vNodes);
375             for(auto pnode : vNodes)
376                 checkpoint.RelayTo(pnode);
377         }
378         return true;
379     }
380
381     // Is the sync-checkpoint outside maturity window?
382     bool IsMatureSyncCheckpoint()
383     {
384         LOCK(cs_hashSyncCheckpoint);
385         // sync-checkpoint should always be accepted block
386         assert(mapBlockIndex.count(hashSyncCheckpoint));
387         const auto pindexSync = mapBlockIndex[hashSyncCheckpoint];
388         return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
389                 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
390     }
391 }
392
393 void CUnsignedSyncCheckpoint::SetNull()
394 {
395     nVersion = 1;
396     hashCheckpoint = 0;
397 }
398
399 std::string CUnsignedSyncCheckpoint::ToString() const
400 {
401     return strprintf(
402         "CSyncCheckpoint(\n"
403         "    nVersion       = %" PRId32 "\n"
404         "    hashCheckpoint = %s\n"
405         ")\n",
406         nVersion,
407         hashCheckpoint.ToString().c_str());
408 }
409
410 // ppcoin: sync-checkpoint master key
411 const string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
412
413 string CSyncCheckpoint::strMasterPrivKey = "";
414
415 CSyncCheckpoint::CSyncCheckpoint()
416 {
417     SetNull();
418 }
419
420 void CSyncCheckpoint::SetNull()
421 {
422     CUnsignedSyncCheckpoint::SetNull();
423     vchMsg.clear();
424     vchSig.clear();
425 }
426
427 bool CSyncCheckpoint::IsNull() const
428 {
429     return (hashCheckpoint == 0);
430 }
431
432 uint256 CSyncCheckpoint::GetHash() const
433 {
434     return SerializeHash(*this);
435 }
436
437 bool CSyncCheckpoint::RelayTo(CNode* pnode) const
438 {
439     // returns true if wasn't already sent
440     if (pnode->hashCheckpointKnown != hashCheckpoint)
441     {
442         pnode->hashCheckpointKnown = hashCheckpoint;
443         pnode->PushMessage("checkpoint", *this);
444         return true;
445     }
446     return false;
447 }
448
449 // ppcoin: verify signature of sync-checkpoint message
450 bool CSyncCheckpoint::CheckSignature()
451 {
452     CPubKey key(ParseHex(CSyncCheckpoint::strMasterPubKey));
453     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
454         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
455
456     // Now unserialize the data
457     CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
458     sMsg >> *(CUnsignedSyncCheckpoint*)this;
459     return true;
460 }
461
462 // process synchronized checkpoint
463 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
464 {
465     if (!CheckSignature())
466         return false;
467
468     LOCK(Checkpoints::cs_hashSyncCheckpoint);
469     if (!mapBlockIndex.count(hashCheckpoint))
470     {
471         // We haven't received the checkpoint chain, keep the checkpoint as pending
472         Checkpoints::hashPendingCheckpoint = hashCheckpoint;
473         Checkpoints::checkpointMessagePending = *this;
474         printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
475         // Ask this guy to fill in what we're missing
476         if (pfrom)
477         {
478             pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
479             // ask directly as well in case rejected earlier by duplicate
480             // proof-of-stake because getblocks may not get it this time
481             pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
482         }
483         return false;
484     }
485
486     if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
487         return false;
488
489     CTxDB txdb;
490     auto pindexCheckpoint = mapBlockIndex[hashCheckpoint];
491     if (!pindexCheckpoint->IsInMainChain())
492     {
493         // checkpoint chain received but not yet main chain
494         CBlock block;
495         if (!block.ReadFromDisk(pindexCheckpoint))
496             return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
497         if (!block.SetBestChain(txdb, pindexCheckpoint))
498         {
499             Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
500             return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
501         }
502     }
503
504 #ifndef USE_LEVELDB
505     txdb.Close();
506 #endif
507
508     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
509         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
510     Checkpoints::checkpointMessage = *this;
511     Checkpoints::hashPendingCheckpoint = 0;
512     Checkpoints::checkpointMessagePending.SetNull();
513     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
514     return true;
515 }