Restore testnet genesis block
[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 "db.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         return {hashCheckPoint, nTime};
27     }
28
29     //
30     // What makes a good checkpoint block?
31     // + Is surrounded by blocks with reasonable timestamps
32     //   (no blocks before with a timestamp after, none after with
33     //    timestamp before)
34     // + Contains no strange transactions
35     //
36     static MapCheckpoints mapCheckpoints =
37         boost::assign::map_list_of
38         ( 0, initCheckpoint(hashGenesisBlock, 1360105017) )
39         ( 6000, initCheckpoint(uint256("0x000000000945e3c9d8e15df834e802521eb79f9ceb4191a27bdfadad4b777f4a"), 1360814368) )
40         ( 9690, initCheckpoint(uint256("0x00000000026561450859c46868099e0df6068a538f038cb18988fd8d47dcdaf5"), 1362791423) )
41         ( 13560, initCheckpoint(uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052) )
42         ( 14189, initCheckpoint(uint256("0x00000000020f76474d2522b19c7bfafc43ba6ecbabae54293bcd9546159c8c1d"), 1365215020) )
43         ( 19600, initCheckpoint(uint256("0x252ae08d6df4bc7220c1dcdaed7b8a6e78bab05a60173511e8f565a3a38ce3c3"), 1367840555) )
44         ( 21800, initCheckpoint(uint256("0x64bdeb35023f240ed01beaa082f840f2d4cc6defccbbcda1260de87e58296b37"), 1368888542) )
45         ( 26174, initCheckpoint(uint256("0x00000000006cf1bfaa0d73caea92f6d2afa465651a76415b8d53b0bb0e01a8be"), 1371039324) )
46         ( 27451, initCheckpoint(uint256("0xd65424c24041b9f2e531f8f275f1a3c8bb105f0b29005b0bd577ae1a73341080"), 1371687462) )
47         ( 37092, initCheckpoint(uint256("0x0000000000a38c2f98556f46793b453e92d8fab2d31c0b93fd08bcf78e56099d"), 1376677203) )
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         txdb.Close();
167
168         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
169         return true;
170     }
171
172     bool AcceptPendingSyncCheckpoint()
173     {
174         LOCK(cs_hashSyncCheckpoint);
175         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
176         {
177             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
178             {
179                 hashPendingCheckpoint = 0;
180                 checkpointMessagePending.SetNull();
181                 return false;
182             }
183
184             CTxDB txdb;
185             CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
186             if (!pindexCheckpoint->IsInMainChain())
187             {
188                 CBlock block;
189                 if (!block.ReadFromDisk(pindexCheckpoint))
190                     return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
191                 if (!block.SetBestChain(txdb, pindexCheckpoint))
192                 {
193                     hashInvalidCheckpoint = hashPendingCheckpoint;
194                     return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
195                 }
196             }
197             txdb.Close();
198
199             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
200                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
201             hashPendingCheckpoint = 0;
202             checkpointMessage = checkpointMessagePending;
203             checkpointMessagePending.SetNull();
204             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
205             // relay the checkpoint
206             if (!checkpointMessage.IsNull())
207             {
208                 BOOST_FOREACH(CNode* pnode, vNodes)
209                     checkpointMessage.RelayTo(pnode);
210             }
211             return true;
212         }
213         return false;
214     }
215
216     // Automatically select a suitable sync-checkpoint 
217     uint256 AutoSelectSyncCheckpoint()
218     {
219         // Proof-of-work blocks are immediately checkpointed
220         // to defend against 51% attack which rejects other miners block 
221
222         // Select the last proof-of-work block
223         const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
224         // Search forward for a block within max span and maturity window
225         while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
226             pindex = pindex->pnext;
227         return pindex->GetBlockHash();
228     }
229
230     // Check against synchronized checkpoint
231     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
232     {
233         if (fTestNet) return true; // Testnet has no checkpoints
234         int nHeight = pindexPrev->nHeight + 1;
235
236         LOCK(cs_hashSyncCheckpoint);
237         // sync-checkpoint should always be accepted block
238         assert(mapBlockIndex.count(hashSyncCheckpoint));
239         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
240
241         if (nHeight > pindexSync->nHeight)
242         {
243             // trace back to same height as sync-checkpoint
244             const CBlockIndex* pindex = pindexPrev;
245             while (pindex->nHeight > pindexSync->nHeight)
246                 if (!(pindex = pindex->pprev))
247                     return error("CheckSync: pprev null - block index structure failure");
248             if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
249                 return false; // only descendant of sync-checkpoint can pass check
250         }
251         if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
252             return false; // same height with sync-checkpoint
253         if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
254             return false; // lower height than sync-checkpoint
255         return true;
256     }
257
258     bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
259     {
260         LOCK(cs_hashSyncCheckpoint);
261         if (hashPendingCheckpoint == 0)
262             return false;
263         if (hashBlock == hashPendingCheckpoint)
264             return true;
265         if (mapOrphanBlocks.count(hashPendingCheckpoint) 
266             && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
267             return true;
268         return false;
269     }
270
271     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
272     bool ResetSyncCheckpoint()
273     {
274         LOCK(cs_hashSyncCheckpoint);
275         const uint256& hash = mapCheckpoints.rbegin()->second.hashCheckPoint;
276         if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
277         {
278             // checkpoint block accepted but not yet in main chain
279             printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
280             CTxDB txdb;
281             CBlock block;
282             if (!block.ReadFromDisk(mapBlockIndex[hash]))
283                 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
284             if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
285             {
286                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
287             }
288             txdb.Close();
289         }
290         else if(!mapBlockIndex.count(hash))
291         {
292             // checkpoint block not yet accepted
293             hashPendingCheckpoint = hash;
294             checkpointMessagePending.SetNull();
295             printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
296         }
297
298         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
299         {
300             const uint256& hash = i.second.hashCheckPoint;
301             if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
302             {
303                 if (!WriteSyncCheckpoint(hash))
304                     return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
305                 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
306                 return true;
307             }
308         }
309
310         return false;
311     }
312
313     void AskForPendingSyncCheckpoint(CNode* pfrom)
314     {
315         LOCK(cs_hashSyncCheckpoint);
316         if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
317             pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
318     }
319
320     bool SetCheckpointPrivKey(std::string strPrivKey)
321     {
322         // Test signing a sync-checkpoint with genesis block
323         CSyncCheckpoint checkpoint;
324         checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
325         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
326         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
327         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
328
329         std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
330         CKey key;
331         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
332         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
333             return false;
334
335         // Test signing successful, proceed
336         CSyncCheckpoint::strMasterPrivKey = strPrivKey;
337         return true;
338     }
339
340     bool SendSyncCheckpoint(uint256 hashCheckpoint)
341     {
342         CSyncCheckpoint checkpoint;
343         checkpoint.hashCheckpoint = hashCheckpoint;
344         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
345         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
346         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
347
348         if (CSyncCheckpoint::strMasterPrivKey.empty())
349             return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
350         std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
351         CKey key;
352         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
353         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
354             return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
355
356         if(!checkpoint.ProcessSyncCheckpoint(NULL))
357         {
358             printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
359             return false;
360         }
361
362         // Relay checkpoint
363         {
364             LOCK(cs_vNodes);
365             BOOST_FOREACH(CNode* pnode, vNodes)
366                 checkpoint.RelayTo(pnode);
367         }
368         return true;
369     }
370
371     // Is the sync-checkpoint outside maturity window?
372     bool IsMatureSyncCheckpoint()
373     {
374         LOCK(cs_hashSyncCheckpoint);
375         // sync-checkpoint should always be accepted block
376         assert(mapBlockIndex.count(hashSyncCheckpoint));
377         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
378         return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
379                 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
380     }
381
382     // Is the sync-checkpoint too old?
383     bool IsSyncCheckpointTooOld(unsigned int nSeconds)
384     {
385         LOCK(cs_hashSyncCheckpoint);
386         // sync-checkpoint should always be accepted block
387         assert(mapBlockIndex.count(hashSyncCheckpoint));
388         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
389         return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
390     }
391 }
392
393 // ppcoin: sync-checkpoint master key
394 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
395
396 std::string CSyncCheckpoint::strMasterPrivKey = "";
397
398 // ppcoin: verify signature of sync-checkpoint message
399 bool CSyncCheckpoint::CheckSignature()
400 {
401     CKey key;
402     if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
403         return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
404     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
405         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
406
407     // Now unserialize the data
408     CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
409     sMsg >> *(CUnsignedSyncCheckpoint*)this;
410     return true;
411 }
412
413 // ppcoin: process synchronized checkpoint
414 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
415 {
416     if (!CheckSignature())
417         return false;
418
419     LOCK(Checkpoints::cs_hashSyncCheckpoint);
420     if (!mapBlockIndex.count(hashCheckpoint))
421     {
422         // We haven't received the checkpoint chain, keep the checkpoint as pending
423         Checkpoints::hashPendingCheckpoint = hashCheckpoint;
424         Checkpoints::checkpointMessagePending = *this;
425         printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
426         // Ask this guy to fill in what we're missing
427         if (pfrom)
428         {
429             pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
430             // ask directly as well in case rejected earlier by duplicate
431             // proof-of-stake because getblocks may not get it this time
432             pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
433         }
434         return false;
435     }
436
437     if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
438         return false;
439
440     CTxDB txdb;
441     CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
442     if (!pindexCheckpoint->IsInMainChain())
443     {
444         // checkpoint chain received but not yet main chain
445         CBlock block;
446         if (!block.ReadFromDisk(pindexCheckpoint))
447             return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
448         if (!block.SetBestChain(txdb, pindexCheckpoint))
449         {
450             Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
451             return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
452         }
453     }
454     txdb.Close();
455
456     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
457         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
458     Checkpoints::checkpointMessage = *this;
459     Checkpoints::hashPendingCheckpoint = 0;
460     Checkpoints::checkpointMessagePending.SetNull();
461     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
462     return true;
463 }