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