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