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