f26168795fddb71a6c7e1b53489f79faa8601463
[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         ( 68600, std::make_pair(uint256("0xb646b0562080ab9411f85d4b2a1ca8b197c67ae170c5e328406871b44233cb06"), 1389867276) )
29         ( 92161, std::make_pair(uint256("0x000000000079090eb31e7fa55487e4e666466253e68b213f44b7977ea7a2eeec"), 1398919969) )
30         ( 98661, std::make_pair(uint256("0x48328dfc0eaffc659723739c6202854d1624449340193bdea3e71ece4ccdd43f"), 1401469019) )
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     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         {
141             LOCK(Checkpoints::cs_hashSyncCheckpoint);
142
143             if (!pblocktree->WriteSyncCheckpoint(hashCheckpoint))
144             {
145                 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
146             }
147         }
148
149         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
150         return true;
151     }
152
153     bool AcceptPendingSyncCheckpoint()
154     {
155         LOCK(cs_hashSyncCheckpoint);
156         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
157         {
158             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
159             {
160                 hashPendingCheckpoint = 0;
161                 checkpointMessagePending.SetNull();
162                 return false;
163             }
164
165             CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
166             if (!pindexCheckpoint->IsInMainChain())
167             {
168                 CBlock block;
169                 if (!block.ReadFromDisk(pindexCheckpoint))
170                     return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
171                 if (!SetBestChain(pindexCheckpoint))
172                 {
173                     hashInvalidCheckpoint = hashPendingCheckpoint;
174                     return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
175                 }
176             }
177
178             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
179                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
180             hashPendingCheckpoint = 0;
181             checkpointMessage = checkpointMessagePending;
182             checkpointMessagePending.SetNull();
183             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
184             // relay the checkpoint
185             if (!checkpointMessage.IsNull())
186             {
187                 BOOST_FOREACH(CNode* pnode, vNodes)
188                     checkpointMessage.RelayTo(pnode);
189             }
190             return true;
191         }
192         return false;
193     }
194
195     // Automatically select a suitable sync-checkpoint 
196     uint256 AutoSelectSyncCheckpoint()
197     {
198         const CBlockIndex *pindex = pindexBest;
199         // Search backward for a block within max span and maturity window
200         while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
201             pindex = pindex->pprev;
202         return pindex->GetBlockHash();
203     }
204
205     // Check against synchronized checkpoint
206     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
207     {
208         if (fTestNet) return true; // Testnet has no checkpoints
209         int nHeight = pindexPrev->nHeight + 1;
210
211         LOCK(cs_hashSyncCheckpoint);
212         // sync-checkpoint should always be accepted block
213         assert(mapBlockIndex.count(hashSyncCheckpoint));
214         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
215
216         if (nHeight > pindexSync->nHeight)
217         {
218             // trace back to same height as sync-checkpoint
219             const CBlockIndex* pindex = pindexPrev;
220             while (pindex->nHeight > pindexSync->nHeight)
221                 if (!(pindex = pindex->pprev))
222                     return error("CheckSync: pprev null - block index structure failure");
223             if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
224                 return false; // only descendant of sync-checkpoint can pass check
225         }
226         if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
227             return false; // same height with sync-checkpoint
228         if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
229             return false; // lower height than sync-checkpoint
230         return true;
231     }
232
233     bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
234     {
235         LOCK(cs_hashSyncCheckpoint);
236         if (hashPendingCheckpoint == 0)
237             return false;
238         if (hashBlock == hashPendingCheckpoint)
239             return true;
240         if (mapOrphanBlocks.count(hashPendingCheckpoint) 
241             && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
242             return true;
243         return false;
244     }
245
246     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
247     bool ResetSyncCheckpoint()
248     {
249         LOCK(cs_hashSyncCheckpoint);
250         const uint256& hash = mapCheckpoints.rbegin()->second.first;
251         if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
252         {
253             // checkpoint block accepted but not yet in main chain
254             printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
255             CBlock block;
256             if (!block.ReadFromDisk(mapBlockIndex[hash]))
257                 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
258             if (!SetBestChain(mapBlockIndex[hash]))
259             {
260                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
261             }
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.first;
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 = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
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 + nCoinbaseMaturity ||
352                 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
353     }
354
355     // Is the sync-checkpoint too old?
356     bool IsSyncCheckpointTooOld(unsigned int nSeconds)
357     {
358         LOCK(cs_hashSyncCheckpoint);
359         // sync-checkpoint should always be accepted block
360         assert(mapBlockIndex.count(hashSyncCheckpoint));
361         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
362         return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
363     }
364 }
365
366 // ppcoin: sync-checkpoint master key
367 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
368
369 std::string CSyncCheckpoint::strMasterPrivKey = "";
370
371 // ppcoin: verify signature of sync-checkpoint message
372 bool CSyncCheckpoint::CheckSignature()
373 {
374     CKey key;
375     if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
376         return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
377     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
378         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
379
380     // Now unserialize the data
381     CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
382     sMsg >> *(CUnsignedSyncCheckpoint*)this;
383     return true;
384 }
385
386 // ppcoin: process synchronized checkpoint
387 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
388 {
389     if (!CheckSignature())
390         return false;
391
392     LOCK(Checkpoints::cs_hashSyncCheckpoint);
393     if (!mapBlockIndex.count(hashCheckpoint))
394     {
395         // We haven't received the checkpoint chain, keep the checkpoint as pending
396         Checkpoints::hashPendingCheckpoint = hashCheckpoint;
397         Checkpoints::checkpointMessagePending = *this;
398         printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
399         // Ask this guy to fill in what we're missing
400         if (pfrom)
401         {
402             pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
403             // ask directly as well in case rejected earlier by duplicate
404             // proof-of-stake because getblocks may not get it this time
405             pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
406         }
407         return false;
408     }
409
410     if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
411         return false;
412
413     CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
414     if (!pindexCheckpoint->IsInMainChain())
415     {
416         // checkpoint chain received but not yet main chain
417         CBlock block;
418         if (!block.ReadFromDisk(pindexCheckpoint))
419             return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
420         if (!SetBestChain(pindexCheckpoint))
421         {
422             Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
423             return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
424         }
425     }
426
427     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
428         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
429     Checkpoints::checkpointMessage = *this;
430     Checkpoints::hashPendingCheckpoint = 0;
431     Checkpoints::checkpointMessagePending.SetNull();
432     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
433     return true;
434 }