281ef318a7e14fc1c6c6a16ef8d5982d78afef06
[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 "db.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         ( 65000, std::make_pair(uint256("0xb646b0562080ab9411f85d4b2a1ca8b197c67ae170c5e328406871b44233cb06"), 1389867276) )
29     ;
30
31     // TestNet has no checkpoints
32     static MapCheckpoints mapCheckpointsTestnet =
33         boost::assign::map_list_of
34         ( 0, std::make_pair(hashGenesisBlockTestNet, 1360105017) )
35         ;
36
37     bool CheckHardened(int nHeight, const uint256& hash)
38     {
39         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
40
41         MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
42         if (i == checkpoints.end()) return true;
43         return hash == i->second.first;
44     }
45
46     int GetTotalBlocksEstimate()
47     {
48         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
49
50         return checkpoints.rbegin()->first;
51     }
52
53     int GetLastCheckpointTime()
54     {
55         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
56
57         return checkpoints.rbegin()->second.second;
58     }
59
60     CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
61     {
62         MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
63
64         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
65         {
66             const uint256& hash = i.second.first;
67             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
68             if (t != mapBlockIndex.end())
69                 return t->second;
70         }
71         return NULL;
72     }
73
74     // ppcoin: synchronized checkpoint (centrally broadcasted)
75     uint256 hashSyncCheckpoint = 0;
76     uint256 hashPendingCheckpoint = 0;
77     CSyncCheckpoint checkpointMessage;
78     CSyncCheckpoint checkpointMessagePending;
79     uint256 hashInvalidCheckpoint = 0;
80     CCriticalSection cs_hashSyncCheckpoint;
81
82     // ppcoin: get last synchronized checkpoint
83     CBlockIndex* GetLastSyncCheckpoint()
84     {
85         LOCK(cs_hashSyncCheckpoint);
86         if (!mapBlockIndex.count(hashSyncCheckpoint))
87             error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
88         else
89             return mapBlockIndex[hashSyncCheckpoint];
90         return NULL;
91     }
92
93     // ppcoin: only descendant of current sync-checkpoint is allowed
94     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
95     {
96         if (!mapBlockIndex.count(hashSyncCheckpoint))
97             return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
98         if (!mapBlockIndex.count(hashCheckpoint))
99             return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
100
101         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
102         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
103
104         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
105         {
106             // Received an older checkpoint, trace back from current checkpoint
107             // to the same height of the received checkpoint to verify
108             // that current checkpoint should be a descendant block
109             CBlockIndex* pindex = pindexSyncCheckpoint;
110             while (pindex->nHeight > pindexCheckpointRecv->nHeight)
111                 if (!(pindex = pindex->pprev))
112                     return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
113             if (pindex->GetBlockHash() != hashCheckpoint)
114             {
115                 hashInvalidCheckpoint = hashCheckpoint;
116                 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
117             }
118             return false; // ignore older checkpoint
119         }
120
121         // Received checkpoint should be a descendant block of the current
122         // checkpoint. Trace back to the same height of current checkpoint
123         // to verify.
124         CBlockIndex* pindex = pindexCheckpointRecv;
125         while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
126             if (!(pindex = pindex->pprev))
127                 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
128         if (pindex->GetBlockHash() != hashSyncCheckpoint)
129         {
130             hashInvalidCheckpoint = hashCheckpoint;
131             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
132         }
133         return true;
134     }
135
136     bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
137     {
138         CChainDB chaindb;
139         chaindb.TxnBegin();
140         if (!chaindb.WriteSyncCheckpoint(hashCheckpoint))
141         {
142             chaindb.TxnAbort();
143             return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
144         }
145         if (!chaindb.TxnCommit())
146             return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
147
148         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
149         return true;
150     }
151
152     bool AcceptPendingSyncCheckpoint()
153     {
154         LOCK(cs_hashSyncCheckpoint);
155         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
156         {
157             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
158             {
159                 hashPendingCheckpoint = 0;
160                 checkpointMessagePending.SetNull();
161                 return false;
162             }
163
164             CChainDB chaindb;
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 (!block.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             CChainDB chaindb;
256             CBlock block;
257             if (!block.ReadFromDisk(mapBlockIndex[hash]))
258                 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
259             if (!block.SetBestChain(mapBlockIndex[hash]))
260             {
261                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
262             }
263         }
264         else if(!mapBlockIndex.count(hash))
265         {
266             // checkpoint block not yet accepted
267             hashPendingCheckpoint = hash;
268             checkpointMessagePending.SetNull();
269             printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
270         }
271
272         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
273         {
274             const uint256& hash = i.second.first;
275             if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
276             {
277                 if (!WriteSyncCheckpoint(hash))
278                     return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
279                 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
280                 return true;
281             }
282         }
283
284         return false;
285     }
286
287     void AskForPendingSyncCheckpoint(CNode* pfrom)
288     {
289         LOCK(cs_hashSyncCheckpoint);
290         if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
291             pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
292     }
293
294     bool SetCheckpointPrivKey(std::string strPrivKey)
295     {
296         // Test signing a sync-checkpoint with genesis block
297         CSyncCheckpoint checkpoint;
298         checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
299         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
300         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
301         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
302
303         std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
304         CKey key;
305         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
306         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
307             return false;
308
309         // Test signing successful, proceed
310         CSyncCheckpoint::strMasterPrivKey = strPrivKey;
311         return true;
312     }
313
314     bool SendSyncCheckpoint(uint256 hashCheckpoint)
315     {
316         CSyncCheckpoint checkpoint;
317         checkpoint.hashCheckpoint = hashCheckpoint;
318         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
319         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
320         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
321
322         if (CSyncCheckpoint::strMasterPrivKey.empty())
323             return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
324         std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
325         CKey key;
326         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
327         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
328             return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
329
330         if(!checkpoint.ProcessSyncCheckpoint(NULL))
331         {
332             printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
333             return false;
334         }
335
336         // Relay checkpoint
337         {
338             LOCK(cs_vNodes);
339             BOOST_FOREACH(CNode* pnode, vNodes)
340                 checkpoint.RelayTo(pnode);
341         }
342         return true;
343     }
344
345     // Is the sync-checkpoint outside maturity window?
346     bool IsMatureSyncCheckpoint()
347     {
348         LOCK(cs_hashSyncCheckpoint);
349         // sync-checkpoint should always be accepted block
350         assert(mapBlockIndex.count(hashSyncCheckpoint));
351         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
352         return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
353                 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
354     }
355
356     // Is the sync-checkpoint too old?
357     bool IsSyncCheckpointTooOld(unsigned int nSeconds)
358     {
359         LOCK(cs_hashSyncCheckpoint);
360         // sync-checkpoint should always be accepted block
361         assert(mapBlockIndex.count(hashSyncCheckpoint));
362         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
363         return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
364     }
365 }
366
367 // ppcoin: sync-checkpoint master key
368 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
369
370 std::string CSyncCheckpoint::strMasterPrivKey = "";
371
372 // ppcoin: verify signature of sync-checkpoint message
373 bool CSyncCheckpoint::CheckSignature()
374 {
375     CKey key;
376     if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
377         return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
378     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
379         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
380
381     // Now unserialize the data
382     CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
383     sMsg >> *(CUnsignedSyncCheckpoint*)this;
384     return true;
385 }
386
387 // ppcoin: process synchronized checkpoint
388 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
389 {
390     if (!CheckSignature())
391         return false;
392
393     LOCK(Checkpoints::cs_hashSyncCheckpoint);
394     if (!mapBlockIndex.count(hashCheckpoint))
395     {
396         // We haven't received the checkpoint chain, keep the checkpoint as pending
397         Checkpoints::hashPendingCheckpoint = hashCheckpoint;
398         Checkpoints::checkpointMessagePending = *this;
399         printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
400         // Ask this guy to fill in what we're missing
401         if (pfrom)
402         {
403             pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
404             // ask directly as well in case rejected earlier by duplicate
405             // proof-of-stake because getblocks may not get it this time
406             pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
407         }
408         return false;
409     }
410
411     if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
412         return false;
413
414     CChainDB chaindb;
415     CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
416     if (!pindexCheckpoint->IsInMainChain())
417     {
418         // checkpoint chain received but not yet main chain
419         CBlock block;
420         if (!block.ReadFromDisk(pindexCheckpoint))
421             return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
422         if (!block.SetBestChain(pindexCheckpoint))
423         {
424             Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
425             return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
426         }
427     }
428
429     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
430         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
431     Checkpoints::checkpointMessage = *this;
432     Checkpoints::hashPendingCheckpoint = 0;
433     Checkpoints::checkpointMessagePending.SetNull();
434     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
435     return true;
436 }