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