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