Add 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 "db.h"
11 #include "main.h"
12 #include "uint256.h"
13
14 namespace Checkpoints
15 {
16     typedef std::map<int, uint256> 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, hashGenesisBlock )
28         ( 6000, uint256("0x000000000945e3c9d8e15df834e802521eb79f9ceb4191a27bdfadad4b777f4a"))
29         ( 9690, uint256("0x00000000026561450859c46868099e0df6068a538f038cb18988fd8d47dcdaf5"))
30         ( 13560, uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"))
31         ( 14189, uint256("0x00000000020f76474d2522b19c7bfafc43ba6ecbabae54293bcd9546159c8c1d"))
32         ( 19600, uint256("0x252ae08d6df4bc7220c1dcdaed7b8a6e78bab05a60173511e8f565a3a38ce3c3"))
33         ( 21800, uint256("0x64bdeb35023f240ed01beaa082f840f2d4cc6defccbbcda1260de87e58296b37"))
34         ( 26174, uint256("0x00000000006cf1bfaa0d73caea92f6d2afa465651a76415b8d53b0bb0e01a8be"))
35         ;
36
37     // TestNet has no checkpoints
38     static MapCheckpoints mapCheckpointsTestnet =
39         boost::assign::map_list_of
40         ( 0, hashGenesisBlockTestNet )
41         ;
42
43     bool CheckHardened(int nHeight, const uint256& hash)
44     {
45         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
46
47         MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
48         if (i == checkpoints.end()) return true;
49         return hash == i->second;
50     }
51
52     int GetTotalBlocksEstimate()
53     {
54         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
55
56         return checkpoints.rbegin()->first;
57     }
58
59     CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
60     {
61         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
62
63         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
64         {
65             const uint256& hash = i.second;
66             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
67             if (t != mapBlockIndex.end())
68                 return t->second;
69         }
70         return NULL;
71     }
72
73     // ppcoin: synchronized checkpoint (centrally broadcasted)
74     uint256 hashSyncCheckpoint = 0;
75     uint256 hashPendingCheckpoint = 0;
76     CSyncCheckpoint checkpointMessage;
77     CSyncCheckpoint checkpointMessagePending;
78     uint256 hashInvalidCheckpoint = 0;
79     CCriticalSection cs_hashSyncCheckpoint;
80
81     // ppcoin: get last synchronized checkpoint
82     CBlockIndex* GetLastSyncCheckpoint()
83     {
84         LOCK(cs_hashSyncCheckpoint);
85         if (!mapBlockIndex.count(hashSyncCheckpoint))
86             error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
87         else
88             return mapBlockIndex[hashSyncCheckpoint];
89         return NULL;
90     }
91
92     // ppcoin: only descendant of current sync-checkpoint is allowed
93     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
94     {
95         if (!mapBlockIndex.count(hashSyncCheckpoint))
96             return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
97         if (!mapBlockIndex.count(hashCheckpoint))
98             return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
99
100         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
101         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
102
103         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
104         {
105             // Received an older checkpoint, trace back from current checkpoint
106             // to the same height of the received checkpoint to verify
107             // that current checkpoint should be a descendant block
108             CBlockIndex* pindex = pindexSyncCheckpoint;
109             while (pindex->nHeight > pindexCheckpointRecv->nHeight)
110                 if (!(pindex = pindex->pprev))
111                     return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
112             if (pindex->GetBlockHash() != hashCheckpoint)
113             {
114                 hashInvalidCheckpoint = hashCheckpoint;
115                 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
116             }
117             return false; // ignore older checkpoint
118         }
119
120         // Received checkpoint should be a descendant block of the current
121         // checkpoint. Trace back to the same height of current checkpoint
122         // to verify.
123         CBlockIndex* pindex = pindexCheckpointRecv;
124         while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
125             if (!(pindex = pindex->pprev))
126                 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
127         if (pindex->GetBlockHash() != hashSyncCheckpoint)
128         {
129             hashInvalidCheckpoint = hashCheckpoint;
130             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
131         }
132         return true;
133     }
134
135     bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
136     {
137         CTxDB txdb;
138         txdb.TxnBegin();
139         if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
140         {
141             txdb.TxnAbort();
142             return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
143         }
144         if (!txdb.TxnCommit())
145             return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
146         txdb.Close();
147
148         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
149         return true;
150     }
151
152     bool AcceptPendingSyncCheckpoint()
153     {
154         LOCK(cs_hashSyncCheckpoint);
155         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
156         {
157             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
158             {
159                 hashPendingCheckpoint = 0;
160                 checkpointMessagePending.SetNull();
161                 return false;
162             }
163
164             CTxDB txdb;
165             CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
166             if (!pindexCheckpoint->IsInMainChain())
167             {
168                 CBlock block;
169                 if (!block.ReadFromDisk(pindexCheckpoint))
170                     return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
171                 if (!block.SetBestChain(txdb, pindexCheckpoint))
172                 {
173                     hashInvalidCheckpoint = hashPendingCheckpoint;
174                     return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
175                 }
176             }
177             txdb.Close();
178
179             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
180                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
181             hashPendingCheckpoint = 0;
182             checkpointMessage = checkpointMessagePending;
183             checkpointMessagePending.SetNull();
184             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
185             // relay the checkpoint
186             if (!checkpointMessage.IsNull())
187             {
188                 BOOST_FOREACH(CNode* pnode, vNodes)
189                     checkpointMessage.RelayTo(pnode);
190             }
191             return true;
192         }
193         return false;
194     }
195
196     // Automatically select a suitable sync-checkpoint 
197     uint256 AutoSelectSyncCheckpoint()
198     {
199         // Proof-of-work blocks are immediately checkpointed
200         // to defend against 51% attack which rejects other miners block 
201
202         // Select the last proof-of-work block
203         const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
204         // Search forward for a block within max span and maturity window
205         while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
206             pindex = pindex->pnext;
207         return pindex->GetBlockHash();
208     }
209
210     // Check against synchronized checkpoint
211     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
212     {
213         if (fTestNet) return true; // Testnet has no checkpoints
214         int nHeight = pindexPrev->nHeight + 1;
215
216         LOCK(cs_hashSyncCheckpoint);
217         // sync-checkpoint should always be accepted block
218         assert(mapBlockIndex.count(hashSyncCheckpoint));
219         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
220
221         if (nHeight > pindexSync->nHeight)
222         {
223             // trace back to same height as sync-checkpoint
224             const CBlockIndex* pindex = pindexPrev;
225             while (pindex->nHeight > pindexSync->nHeight)
226                 if (!(pindex = pindex->pprev))
227                     return error("CheckSync: pprev null - block index structure failure");
228             if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
229                 return false; // only descendant of sync-checkpoint can pass check
230         }
231         if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
232             return false; // same height with sync-checkpoint
233         if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
234             return false; // lower height than sync-checkpoint
235         return true;
236     }
237
238     bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
239     {
240         LOCK(cs_hashSyncCheckpoint);
241         if (hashPendingCheckpoint == 0)
242             return false;
243         if (hashBlock == hashPendingCheckpoint)
244             return true;
245         if (mapOrphanBlocks.count(hashPendingCheckpoint) 
246             && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
247             return true;
248         return false;
249     }
250
251     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
252     bool ResetSyncCheckpoint()
253     {
254         LOCK(cs_hashSyncCheckpoint);
255         const uint256& hash = mapCheckpoints.rbegin()->second;
256         if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
257         {
258             // checkpoint block accepted but not yet in main chain
259             printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
260             CTxDB txdb;
261             CBlock block;
262             if (!block.ReadFromDisk(mapBlockIndex[hash]))
263                 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
264             if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
265             {
266                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
267             }
268             txdb.Close();
269         }
270         else if(!mapBlockIndex.count(hash))
271         {
272             // checkpoint block not yet accepted
273             hashPendingCheckpoint = hash;
274             checkpointMessagePending.SetNull();
275             printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
276         }
277
278         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
279         {
280             const uint256& hash = i.second;
281             if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
282             {
283                 if (!WriteSyncCheckpoint(hash))
284                     return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
285                 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
286                 return true;
287             }
288         }
289
290         return false;
291     }
292
293     void AskForPendingSyncCheckpoint(CNode* pfrom)
294     {
295         LOCK(cs_hashSyncCheckpoint);
296         if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
297             pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
298     }
299
300     bool SetCheckpointPrivKey(std::string strPrivKey)
301     {
302         // Test signing a sync-checkpoint with genesis block
303         CSyncCheckpoint checkpoint;
304         checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
305         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
306         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
307         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
308
309         std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
310         CKey key;
311         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
312         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
313             return false;
314
315         // Test signing successful, proceed
316         CSyncCheckpoint::strMasterPrivKey = strPrivKey;
317         return true;
318     }
319
320     bool SendSyncCheckpoint(uint256 hashCheckpoint)
321     {
322         CSyncCheckpoint checkpoint;
323         checkpoint.hashCheckpoint = hashCheckpoint;
324         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
325         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
326         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
327
328         if (CSyncCheckpoint::strMasterPrivKey.empty())
329             return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
330         std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
331         CKey key;
332         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
333         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
334             return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
335
336         if(!checkpoint.ProcessSyncCheckpoint(NULL))
337         {
338             printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
339             return false;
340         }
341
342         // Relay checkpoint
343         {
344             LOCK(cs_vNodes);
345             BOOST_FOREACH(CNode* pnode, vNodes)
346                 checkpoint.RelayTo(pnode);
347         }
348         return true;
349     }
350
351     // Is the sync-checkpoint outside maturity window?
352     bool IsMatureSyncCheckpoint()
353     {
354         LOCK(cs_hashSyncCheckpoint);
355         // sync-checkpoint should always be accepted block
356         assert(mapBlockIndex.count(hashSyncCheckpoint));
357         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
358         return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
359                 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
360     }
361
362     // Is the sync-checkpoint too old?
363     bool IsSyncCheckpointTooOld(unsigned int nSeconds)
364     {
365         LOCK(cs_hashSyncCheckpoint);
366         // sync-checkpoint should always be accepted block
367         assert(mapBlockIndex.count(hashSyncCheckpoint));
368         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
369         return (pindexSync->GetBlockTime() + nSeconds < 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 // ppcoin: 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     txdb.Close();
435
436     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
437         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
438     Checkpoints::checkpointMessage = *this;
439     Checkpoints::hashPendingCheckpoint = 0;
440     Checkpoints::checkpointMessagePending.SetNull();
441     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
442     return true;
443 }