Checkpoint object replacement with std::pair & support for incompatible database...
[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     ;
34
35     // TestNet has no checkpoints
36     static MapCheckpoints mapCheckpointsTestnet =
37         boost::assign::map_list_of
38         ( 0, std::make_pair(hashGenesisBlockTestNet, 1360105017) )
39         ;
40
41     bool CheckHardened(int nHeight, const uint256& hash)
42     {
43         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
44
45         MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
46         if (i == checkpoints.end()) return true;
47         return hash == i->second.first;
48     }
49
50     int GetTotalBlocksEstimate()
51     {
52         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
53
54         return checkpoints.rbegin()->first;
55     }
56
57     int GetLastCheckpointTime()
58     {
59         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
60
61         return checkpoints.rbegin()->second.second;
62     }
63
64     CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
65     {
66         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
67
68         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
69         {
70             const uint256& hash = i.second.first;
71             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
72             if (t != mapBlockIndex.end())
73                 return t->second;
74         }
75         return NULL;
76     }
77
78     // ppcoin: synchronized checkpoint (centrally broadcasted)
79     uint256 hashSyncCheckpoint = 0;
80     uint256 hashPendingCheckpoint = 0;
81     CSyncCheckpoint checkpointMessage;
82     CSyncCheckpoint checkpointMessagePending;
83     uint256 hashInvalidCheckpoint = 0;
84     CCriticalSection cs_hashSyncCheckpoint;
85
86     // ppcoin: get last synchronized checkpoint
87     CBlockIndex* GetLastSyncCheckpoint()
88     {
89         LOCK(cs_hashSyncCheckpoint);
90         if (!mapBlockIndex.count(hashSyncCheckpoint))
91             error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
92         else
93             return mapBlockIndex[hashSyncCheckpoint];
94         return NULL;
95     }
96
97     // ppcoin: only descendant of current sync-checkpoint is allowed
98     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
99     {
100         if (!mapBlockIndex.count(hashSyncCheckpoint))
101             return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
102         if (!mapBlockIndex.count(hashCheckpoint))
103             return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
104
105         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
106         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
107
108         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
109         {
110             // Received an older checkpoint, trace back from current checkpoint
111             // to the same height of the received checkpoint to verify
112             // that current checkpoint should be a descendant block
113             CBlockIndex* pindex = pindexSyncCheckpoint;
114             while (pindex->nHeight > pindexCheckpointRecv->nHeight)
115                 if (!(pindex = pindex->pprev))
116                     return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
117             if (pindex->GetBlockHash() != hashCheckpoint)
118             {
119                 hashInvalidCheckpoint = hashCheckpoint;
120                 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
121             }
122             return false; // ignore older checkpoint
123         }
124
125         // Received checkpoint should be a descendant block of the current
126         // checkpoint. Trace back to the same height of current checkpoint
127         // to verify.
128         CBlockIndex* pindex = pindexCheckpointRecv;
129         while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
130             if (!(pindex = pindex->pprev))
131                 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
132         if (pindex->GetBlockHash() != hashSyncCheckpoint)
133         {
134             hashInvalidCheckpoint = hashCheckpoint;
135             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
136         }
137         return true;
138     }
139
140     bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
141     {
142         CTxDB txdb;
143         txdb.TxnBegin();
144         if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
145         {
146             txdb.TxnAbort();
147             return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
148         }
149         if (!txdb.TxnCommit())
150             return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
151
152         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
153         return true;
154     }
155
156     bool AcceptPendingSyncCheckpoint()
157     {
158         LOCK(cs_hashSyncCheckpoint);
159         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
160         {
161             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
162             {
163                 hashPendingCheckpoint = 0;
164                 checkpointMessagePending.SetNull();
165                 return false;
166             }
167
168             CTxDB txdb;
169             CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
170             if (!pindexCheckpoint->IsInMainChain())
171             {
172                 CBlock block;
173                 if (!block.ReadFromDisk(pindexCheckpoint))
174                     return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
175                 if (!block.SetBestChain(txdb, pindexCheckpoint))
176                 {
177                     hashInvalidCheckpoint = hashPendingCheckpoint;
178                     return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
179                 }
180             }
181
182             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
183                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
184             hashPendingCheckpoint = 0;
185             checkpointMessage = checkpointMessagePending;
186             checkpointMessagePending.SetNull();
187             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
188             // relay the checkpoint
189             if (!checkpointMessage.IsNull())
190             {
191                 BOOST_FOREACH(CNode* pnode, vNodes)
192                     checkpointMessage.RelayTo(pnode);
193             }
194             return true;
195         }
196         return false;
197     }
198
199     // Automatically select a suitable sync-checkpoint 
200     uint256 AutoSelectSyncCheckpoint()
201     {
202         const CBlockIndex *pindex = pindexBest;
203         // Search backward for a block within max span and maturity window
204         while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
205             pindex = pindex->pprev;
206         return pindex->GetBlockHash();
207     }
208
209     // Check against synchronized checkpoint
210     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
211     {
212         if (fTestNet) return true; // Testnet has no checkpoints
213         int nHeight = pindexPrev->nHeight + 1;
214
215         LOCK(cs_hashSyncCheckpoint);
216         // sync-checkpoint should always be accepted block
217         assert(mapBlockIndex.count(hashSyncCheckpoint));
218         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
219
220         if (nHeight > pindexSync->nHeight)
221         {
222             // trace back to same height as sync-checkpoint
223             const CBlockIndex* pindex = pindexPrev;
224             while (pindex->nHeight > pindexSync->nHeight)
225                 if (!(pindex = pindex->pprev))
226                     return error("CheckSync: pprev null - block index structure failure");
227             if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
228                 return false; // only descendant of sync-checkpoint can pass check
229         }
230         if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
231             return false; // same height with sync-checkpoint
232         if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
233             return false; // lower height than sync-checkpoint
234         return true;
235     }
236
237     bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
238     {
239         LOCK(cs_hashSyncCheckpoint);
240         if (hashPendingCheckpoint == 0)
241             return false;
242         if (hashBlock == hashPendingCheckpoint)
243             return true;
244         if (mapOrphanBlocks.count(hashPendingCheckpoint) 
245             && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
246             return true;
247         return false;
248     }
249
250     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
251     bool ResetSyncCheckpoint()
252     {
253         LOCK(cs_hashSyncCheckpoint);
254         const uint256& hash = mapCheckpoints.rbegin()->second.first;
255         if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
256         {
257             // checkpoint block accepted but not yet in main chain
258             printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
259             CTxDB txdb;
260             CBlock block;
261             if (!block.ReadFromDisk(mapBlockIndex[hash]))
262                 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
263             if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
264             {
265                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
266             }
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.first;
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 = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
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
433     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
434         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
435     Checkpoints::checkpointMessage = *this;
436     Checkpoints::hashPendingCheckpoint = 0;
437     Checkpoints::checkpointMessagePending.SetNull();
438     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
439     return true;
440 }