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