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