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