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