PPCoin: No safe mode when detecting longer invalid chain
[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                 txdb.TxnBegin();
162                 if (!Reorganize(txdb, pindexCheckpoint))
163                 {
164                     txdb.TxnAbort();
165                     hashInvalidCheckpoint = hashPendingCheckpoint;
166                     return error("AcceptPendingSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
167                 }
168             }
169             txdb.Close();
170
171             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
172                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
173             hashPendingCheckpoint = 0;
174             checkpointMessage = checkpointMessagePending;
175             checkpointMessagePending.SetNull();
176             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
177             // relay the checkpoint
178             if (!checkpointMessage.IsNull())
179             {
180                 BOOST_FOREACH(CNode* pnode, vNodes)
181                     checkpointMessage.RelayTo(pnode);
182             }
183             return true;
184         }
185         return false;
186     }
187
188     // Automatically select a suitable sync-checkpoint 
189     uint256 AutoSelectSyncCheckpoint()
190     {
191         // Proof-of-work blocks are immediately checkpointed
192         // to defend against 51% attack which rejects other miners block 
193
194         // Select the last proof-of-work block
195         const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
196         // Search forward for a block within max span and maturity window
197         while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + COINBASE_MATURITY - 20 <= pindexBest->nHeight))
198             pindex = pindex->pnext;
199         return pindex->GetBlockHash();
200     }
201
202     // Check against synchronized checkpoint
203     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
204     {
205         if (fTestNet) return true; // Testnet has no checkpoints
206         int nHeight = pindexPrev->nHeight + 1;
207
208         LOCK(cs_hashSyncCheckpoint);
209         // sync-checkpoint should always be accepted block
210         assert(mapBlockIndex.count(hashSyncCheckpoint));
211         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
212
213         if (nHeight > pindexSync->nHeight)
214         {
215             // trace back to same height as sync-checkpoint
216             const CBlockIndex* pindex = pindexPrev;
217             while (pindex->nHeight > pindexSync->nHeight)
218                 if (!(pindex = pindex->pprev))
219                     return error("CheckSync: pprev null - block index structure failure");
220             if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
221                 return false; // only descendant of sync-checkpoint can pass check
222         }
223         if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
224             return false; // same height with sync-checkpoint
225         if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
226             return false; // lower height than sync-checkpoint
227         return true;
228     }
229
230     bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
231     {
232         LOCK(cs_hashSyncCheckpoint);
233         if (hashPendingCheckpoint == 0)
234             return false;
235         if (hashBlock == hashPendingCheckpoint)
236             return true;
237         if (mapOrphanBlocks.count(hashPendingCheckpoint) 
238             && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
239             return true;
240         return false;
241     }
242
243     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
244     bool ResetSyncCheckpoint()
245     {
246         LOCK(cs_hashSyncCheckpoint);
247         const uint256& hash = mapCheckpoints.rbegin()->second;
248         if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
249         {
250             // checkpoint block accepted but not yet in main chain
251             printf("ResetSyncCheckpoint: Reorganize to hardened checkpoint %s\n", hash.ToString().c_str());
252             CTxDB txdb;
253             txdb.TxnBegin();
254             if (!Reorganize(txdb, mapBlockIndex[hash]))
255             {
256                 txdb.TxnAbort();
257                 return error("ResetSyncCheckpoint: Reorganize failed for hardened checkpoint %s", hash.ToString().c_str());
258             }
259             txdb.Close();
260         }
261         else if(!mapBlockIndex.count(hash))
262         {
263             // checkpoint block not yet accepted
264             hashPendingCheckpoint = hash;
265             checkpointMessagePending.SetNull();
266             printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
267         }
268
269         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
270         {
271             const uint256& hash = i.second;
272             if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
273             {
274                 if (!WriteSyncCheckpoint(hash))
275                     return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
276                 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
277                 return true;
278             }
279         }
280
281         return false;
282     }
283
284     void AskForPendingSyncCheckpoint(CNode* pfrom)
285     {
286         LOCK(cs_hashSyncCheckpoint);
287         if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
288             pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
289     }
290
291     bool SetCheckpointPrivKey(std::string strPrivKey)
292     {
293         // Test signing a sync-checkpoint with genesis block
294         CSyncCheckpoint checkpoint;
295         checkpoint.hashCheckpoint = hashGenesisBlock;
296         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
297         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
298         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
299
300         std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
301         CKey key;
302         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
303         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
304             return false;
305
306         // Test signing successful, proceed
307         CSyncCheckpoint::strMasterPrivKey = strPrivKey;
308         return true;
309     }
310
311     bool SendSyncCheckpoint(uint256 hashCheckpoint)
312     {
313         CSyncCheckpoint checkpoint;
314         checkpoint.hashCheckpoint = hashCheckpoint;
315         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
316         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
317         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
318
319         if (CSyncCheckpoint::strMasterPrivKey.empty())
320             return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
321         std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
322         CKey key;
323         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
324         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
325             return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
326
327         if(!checkpoint.ProcessSyncCheckpoint(NULL))
328         {
329             printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
330             return false;
331         }
332
333         // Relay checkpoint
334         {
335             LOCK(cs_vNodes);
336             BOOST_FOREACH(CNode* pnode, vNodes)
337                 checkpoint.RelayTo(pnode);
338         }
339         return true;
340     }
341
342     // Is the sync-checkpoint outside maturity window?
343     bool IsMatureSyncCheckpoint()
344     {
345         LOCK(cs_hashSyncCheckpoint);
346         // sync-checkpoint should always be accepted block
347         assert(mapBlockIndex.count(hashSyncCheckpoint));
348         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
349         return (nBestHeight >= pindexSync->nHeight + COINBASE_MATURITY);
350     }
351 }
352
353 // ppcoin: sync-checkpoint master key
354 const std::string CSyncCheckpoint::strMasterPubKey = "0424f20205e5da98ba632bbd278a11a6499585f62bfb2c782377ef59f0251daab8085fc31471bcb8180bc75ed0fa41bb50c7c084511d54015a3a5241d645c7268a";
355
356 std::string CSyncCheckpoint::strMasterPrivKey = "";
357
358 // ppcoin: verify signature of sync-checkpoint message
359 bool CSyncCheckpoint::CheckSignature()
360 {
361     CKey key;
362     if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
363         return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
364     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
365         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
366
367     // Now unserialize the data
368     CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
369     sMsg >> *(CUnsignedSyncCheckpoint*)this;
370     return true;
371 }
372
373 // ppcoin: process synchronized checkpoint
374 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
375 {
376     if (!CheckSignature())
377         return false;
378
379     LOCK(Checkpoints::cs_hashSyncCheckpoint);
380     if (!mapBlockIndex.count(hashCheckpoint))
381     {
382         // We haven't received the checkpoint chain, keep the checkpoint as pending
383         Checkpoints::hashPendingCheckpoint = hashCheckpoint;
384         Checkpoints::checkpointMessagePending = *this;
385         printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
386         // Ask this guy to fill in what we're missing
387         if (pfrom)
388         {
389             pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
390             // ask directly as well in case rejected earlier by duplicate
391             // proof-of-stake because getblocks may not get it this time
392             pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
393         }
394         return false;
395     }
396
397     if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
398         return false;
399
400     CTxDB txdb;
401     CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
402     if (!pindexCheckpoint->IsInMainChain())
403     {
404         // checkpoint chain received but not yet main chain
405         txdb.TxnBegin();
406         if (!Reorganize(txdb, pindexCheckpoint))
407         {
408             txdb.TxnAbort();
409             Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
410             return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
411         }
412     }
413     txdb.Close();
414
415     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
416         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
417     Checkpoints::checkpointMessage = *this;
418     Checkpoints::hashPendingCheckpoint = 0;
419     Checkpoints::checkpointMessagePending.SetNull();
420     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
421     return true;
422 }