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