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