Add checkpoint at block #200000
[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         ( 13560, std::make_pair(uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052) )
29         ( 143990, std::make_pair(uint256("0x00000000001ff5c3940a9f73ad4a990f64955179bde0f743c76dbf0031429efc"), 1418953493) )
30         ( 149000, std::make_pair(uint256("0x7a24acfcadcf43054e7f7d9f273522c0dfc5791ba4006e0273e7521a8d36c525"), 1420872125) )
31         ( 160000, std::make_pair(uint256("0x000000000001cb1133043d38d077c0e93f66c8b2566779f10f182137d1e34a68"), 1425150237) )
32         ( 200000, std::make_pair(uint256("0x0000000000029f8bbf66e6ea6f3e5db55009404aae0fe395a53dd33142b2bff2"), 1441127233) )
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     unsigned 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 #ifndef USE_LEVELDB
153         txdb.Close();
154 #endif
155
156         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
157         return true;
158     }
159
160     bool AcceptPendingSyncCheckpoint()
161     {
162         LOCK(cs_hashSyncCheckpoint);
163         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
164         {
165             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
166             {
167                 hashPendingCheckpoint = 0;
168                 checkpointMessagePending.SetNull();
169                 return false;
170             }
171
172             CTxDB txdb;
173             CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
174             if (!pindexCheckpoint->IsInMainChain())
175             {
176                 CBlock block;
177                 if (!block.ReadFromDisk(pindexCheckpoint))
178                     return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
179                 if (!block.SetBestChain(txdb, pindexCheckpoint))
180                 {
181                     hashInvalidCheckpoint = hashPendingCheckpoint;
182                     return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
183                 }
184             }
185
186 #ifndef USE_LEVELDB
187             txdb.Close();
188 #endif
189             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
190                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
191             hashPendingCheckpoint = 0;
192             checkpointMessage = checkpointMessagePending;
193             checkpointMessagePending.SetNull();
194             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
195             // relay the checkpoint
196             if (!checkpointMessage.IsNull())
197             {
198                 BOOST_FOREACH(CNode* pnode, vNodes)
199                     checkpointMessage.RelayTo(pnode);
200             }
201             return true;
202         }
203         return false;
204     }
205
206     // Automatically select a suitable sync-checkpoint 
207     uint256 AutoSelectSyncCheckpoint()
208     {
209         const CBlockIndex *pindex = pindexBest;
210         // Search backward for a block within max span and maturity window
211         while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
212             pindex = pindex->pprev;
213         return pindex->GetBlockHash();
214     }
215
216     // Check against synchronized checkpoint
217     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
218     {
219         if (fTestNet) return true; // Testnet has no checkpoints
220         int nHeight = pindexPrev->nHeight + 1;
221
222         LOCK(cs_hashSyncCheckpoint);
223         // sync-checkpoint should always be accepted block
224         assert(mapBlockIndex.count(hashSyncCheckpoint));
225         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
226
227         if (nHeight > pindexSync->nHeight)
228         {
229             // trace back to same height as sync-checkpoint
230             const CBlockIndex* pindex = pindexPrev;
231             while (pindex->nHeight > pindexSync->nHeight)
232                 if (!(pindex = pindex->pprev))
233                     return error("CheckSync: pprev null - block index structure failure");
234             if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
235                 return false; // only descendant of sync-checkpoint can pass check
236         }
237         if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
238             return false; // same height with sync-checkpoint
239         if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
240             return false; // lower height than sync-checkpoint
241         return true;
242     }
243
244     bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
245     {
246         LOCK(cs_hashSyncCheckpoint);
247         if (hashPendingCheckpoint == 0)
248             return false;
249         if (hashBlock == hashPendingCheckpoint)
250             return true;
251         if (mapOrphanBlocks.count(hashPendingCheckpoint) 
252             && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
253             return true;
254         return false;
255     }
256
257     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
258     bool ResetSyncCheckpoint()
259     {
260         LOCK(cs_hashSyncCheckpoint);
261         const uint256& hash = mapCheckpoints.rbegin()->second.first;
262         if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
263         {
264             // checkpoint block accepted but not yet in main chain
265             printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
266             CTxDB txdb;
267             CBlock block;
268             if (!block.ReadFromDisk(mapBlockIndex[hash]))
269                 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
270             if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
271             {
272                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
273             }
274
275 #ifndef USE_LEVELDB
276             txdb.Close();
277 #endif
278
279         }
280         else if(!mapBlockIndex.count(hash))
281         {
282             // checkpoint block not yet accepted
283             hashPendingCheckpoint = hash;
284             checkpointMessagePending.SetNull();
285             printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
286         }
287
288         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
289         {
290             const uint256& hash = i.second.first;
291             if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
292             {
293                 if (!WriteSyncCheckpoint(hash))
294                     return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
295                 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
296                 return true;
297             }
298         }
299
300         return false;
301     }
302
303     void AskForPendingSyncCheckpoint(CNode* pfrom)
304     {
305         LOCK(cs_hashSyncCheckpoint);
306         if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
307             pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
308     }
309
310     bool SetCheckpointPrivKey(std::string strPrivKey)
311     {
312         // Test signing a sync-checkpoint with genesis block
313         CSyncCheckpoint checkpoint;
314         checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
315         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
316         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
317         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
318
319         std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
320         CKey key;
321         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
322         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
323             return false;
324
325         // Test signing successful, proceed
326         CSyncCheckpoint::strMasterPrivKey = strPrivKey;
327         return true;
328     }
329
330     bool SendSyncCheckpoint(uint256 hashCheckpoint)
331     {
332         CSyncCheckpoint checkpoint;
333         checkpoint.hashCheckpoint = hashCheckpoint;
334         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
335         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
336         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
337
338         if (CSyncCheckpoint::strMasterPrivKey.empty())
339             return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
340         std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
341         CKey key;
342         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
343         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
344             return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
345
346         if(!checkpoint.ProcessSyncCheckpoint(NULL))
347         {
348             printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
349             return false;
350         }
351
352         // Relay checkpoint
353         {
354             LOCK(cs_vNodes);
355             BOOST_FOREACH(CNode* pnode, vNodes)
356                 checkpoint.RelayTo(pnode);
357         }
358         return true;
359     }
360
361     // Is the sync-checkpoint outside maturity window?
362     bool IsMatureSyncCheckpoint()
363     {
364         LOCK(cs_hashSyncCheckpoint);
365         // sync-checkpoint should always be accepted block
366         assert(mapBlockIndex.count(hashSyncCheckpoint));
367         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
368         return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
369                 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
370     }
371 }
372
373 // ppcoin: sync-checkpoint master key
374 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
375
376 std::string CSyncCheckpoint::strMasterPrivKey = "";
377
378 // ppcoin: verify signature of sync-checkpoint message
379 bool CSyncCheckpoint::CheckSignature()
380 {
381     CKey key;
382     if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
383         return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
384     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
385         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
386
387     // Now unserialize the data
388     CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
389     sMsg >> *(CUnsignedSyncCheckpoint*)this;
390     return true;
391 }
392
393 // process synchronized checkpoint
394 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
395 {
396     if (!CheckSignature())
397         return false;
398
399     LOCK(Checkpoints::cs_hashSyncCheckpoint);
400     if (!mapBlockIndex.count(hashCheckpoint))
401     {
402         // We haven't received the checkpoint chain, keep the checkpoint as pending
403         Checkpoints::hashPendingCheckpoint = hashCheckpoint;
404         Checkpoints::checkpointMessagePending = *this;
405         printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
406         // Ask this guy to fill in what we're missing
407         if (pfrom)
408         {
409             pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
410             // ask directly as well in case rejected earlier by duplicate
411             // proof-of-stake because getblocks may not get it this time
412             pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
413         }
414         return false;
415     }
416
417     if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
418         return false;
419
420     CTxDB txdb;
421     CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
422     if (!pindexCheckpoint->IsInMainChain())
423     {
424         // checkpoint chain received but not yet main chain
425         CBlock block;
426         if (!block.ReadFromDisk(pindexCheckpoint))
427             return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
428         if (!block.SetBestChain(txdb, pindexCheckpoint))
429         {
430             Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
431             return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
432         }
433     }
434
435 #ifndef USE_LEVELDB
436     txdb.Close();
437 #endif
438
439     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
440         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
441     Checkpoints::checkpointMessage = *this;
442     Checkpoints::hashPendingCheckpoint = 0;
443     Checkpoints::checkpointMessagePending.SetNull();
444     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
445     return true;
446 }