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