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