add checkpoint
[novacoin.git] / src / checkpoints.cpp
1 // Copyright (c) 2009-2012 The Bitcoin developers
2 // Copyright (c) 2011-2013 The PPCoin developers
3 // Copyright (c) 2013 NovaCoin Developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7 #include <boost/assign/list_of.hpp> // for 'map_list_of()'
8 #include <boost/foreach.hpp>
9
10 #include "checkpoints.h"
11
12 #include "db.h"
13 #include "main.h"
14 #include "uint256.h"
15
16 namespace Checkpoints
17 {
18     typedef std::map<int, uint256> MapCheckpoints;   // hardened checkpoints
19
20     //
21     // What makes a good checkpoint block?
22     // + Is surrounded by blocks with reasonable timestamps
23     //   (no blocks before with a timestamp after, none after with
24     //    timestamp before)
25     // + Contains no strange transactions
26     //
27     static MapCheckpoints mapCheckpoints =
28         boost::assign::map_list_of
29         ( 0, hashGenesisBlockOfficial )
30         ( 6000, uint256("0x000000000945e3c9d8e15df834e802521eb79f9ceb4191a27bdfadad4b777f4a"))
31         ;
32
33     bool CheckHardened(int nHeight, const uint256& hash)
34     {
35         if (fTestNet) return true; // Testnet has no checkpoints
36
37         MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
38         if (i == mapCheckpoints.end()) return true;
39         return hash == i->second;
40     }
41
42     int GetTotalBlocksEstimate()
43     {
44         if (fTestNet) return 0;
45
46         return mapCheckpoints.rbegin()->first;
47     }
48
49     CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
50     {
51         if (fTestNet) {
52             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hashGenesisBlock);
53             if (t != mapBlockIndex.end())
54                 return t->second;
55             return NULL;
56         }
57
58         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
59         {
60             const uint256& hash = i.second;
61             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
62             if (t != mapBlockIndex.end())
63                 return t->second;
64         }
65         return NULL;
66     }
67
68     // ppcoin: synchronized checkpoint (centrally broadcasted)
69     uint256 hashSyncCheckpoint = 0;
70     uint256 hashPendingCheckpoint = 0;
71     CSyncCheckpoint checkpointMessage;
72     CSyncCheckpoint checkpointMessagePending;
73     uint256 hashInvalidCheckpoint = 0;
74     CCriticalSection cs_hashSyncCheckpoint;
75
76     // ppcoin: get last synchronized checkpoint
77     CBlockIndex* GetLastSyncCheckpoint()
78     {
79         LOCK(cs_hashSyncCheckpoint);
80         if (!mapBlockIndex.count(hashSyncCheckpoint))
81             error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
82         else
83             return mapBlockIndex[hashSyncCheckpoint];
84         return NULL;
85     }
86
87     // ppcoin: only descendant of current sync-checkpoint is allowed
88     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
89     {
90         if (!mapBlockIndex.count(hashSyncCheckpoint))
91             return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
92         if (!mapBlockIndex.count(hashCheckpoint))
93             return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
94
95         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
96         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
97
98         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
99         {
100             // Received an older checkpoint, trace back from current checkpoint
101             // to the same height of the received checkpoint to verify
102             // that current checkpoint should be a descendant block
103             CBlockIndex* pindex = pindexSyncCheckpoint;
104             while (pindex->nHeight > pindexCheckpointRecv->nHeight)
105                 if (!(pindex = pindex->pprev))
106                     return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
107             if (pindex->GetBlockHash() != hashCheckpoint)
108             {
109                 hashInvalidCheckpoint = hashCheckpoint;
110                 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
111             }
112             return false; // ignore older checkpoint
113         }
114
115         // Received checkpoint should be a descendant block of the current
116         // checkpoint. Trace back to the same height of current checkpoint
117         // to verify.
118         CBlockIndex* pindex = pindexCheckpointRecv;
119         while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
120             if (!(pindex = pindex->pprev))
121                 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
122         if (pindex->GetBlockHash() != hashSyncCheckpoint)
123         {
124             hashInvalidCheckpoint = hashCheckpoint;
125             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
126         }
127         return true;
128     }
129
130     bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
131     {
132         CTxDB txdb;
133         txdb.TxnBegin();
134         if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
135         {
136             txdb.TxnAbort();
137             return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
138         }
139         if (!txdb.TxnCommit())
140             return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
141         txdb.Close();
142
143         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
144         return true;
145     }
146
147     bool AcceptPendingSyncCheckpoint()
148     {
149         LOCK(cs_hashSyncCheckpoint);
150         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
151         {
152             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
153             {
154                 hashPendingCheckpoint = 0;
155                 checkpointMessagePending.SetNull();
156                 return false;
157             }
158
159             CTxDB txdb;
160             CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
161             if (!pindexCheckpoint->IsInMainChain())
162             {
163                 CBlock block;
164                 if (!block.ReadFromDisk(pindexCheckpoint))
165                     return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
166                 if (!block.SetBestChain(txdb, pindexCheckpoint))
167                 {
168                     hashInvalidCheckpoint = hashPendingCheckpoint;
169                     return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
170                 }
171             }
172             txdb.Close();
173
174             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
175                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
176             hashPendingCheckpoint = 0;
177             checkpointMessage = checkpointMessagePending;
178             checkpointMessagePending.SetNull();
179             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
180             // relay the checkpoint
181             if (!checkpointMessage.IsNull())
182             {
183                 BOOST_FOREACH(CNode* pnode, vNodes)
184                     checkpointMessage.RelayTo(pnode);
185             }
186             return true;
187         }
188         return false;
189     }
190
191     // Automatically select a suitable sync-checkpoint 
192     uint256 AutoSelectSyncCheckpoint()
193     {
194         // Proof-of-work blocks are immediately checkpointed
195         // to defend against 51% attack which rejects other miners block 
196
197         // Select the last proof-of-work block
198         const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
199         // Search forward for a block within max span and maturity window
200         while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
201             pindex = pindex->pnext;
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;
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             CTxDB txdb;
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(txdb, mapBlockIndex[hash]))
260             {
261                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
262             }
263             txdb.Close();
264         }
265         else if(!mapBlockIndex.count(hash))
266         {
267             // checkpoint block not yet accepted
268             hashPendingCheckpoint = hash;
269             checkpointMessagePending.SetNull();
270             printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
271         }
272
273         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
274         {
275             const uint256& hash = i.second;
276             if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
277             {
278                 if (!WriteSyncCheckpoint(hash))
279                     return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
280                 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
281                 return true;
282             }
283         }
284
285         return false;
286     }
287
288     void AskForPendingSyncCheckpoint(CNode* pfrom)
289     {
290         LOCK(cs_hashSyncCheckpoint);
291         if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
292             pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
293     }
294
295     bool SetCheckpointPrivKey(std::string strPrivKey)
296     {
297         // Test signing a sync-checkpoint with genesis block
298         CSyncCheckpoint checkpoint;
299         checkpoint.hashCheckpoint = hashGenesisBlock;
300         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
301         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
302         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
303
304         std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
305         CKey key;
306         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
307         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
308             return false;
309
310         // Test signing successful, proceed
311         CSyncCheckpoint::strMasterPrivKey = strPrivKey;
312         return true;
313     }
314
315     bool SendSyncCheckpoint(uint256 hashCheckpoint)
316     {
317         CSyncCheckpoint checkpoint;
318         checkpoint.hashCheckpoint = hashCheckpoint;
319         CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
320         sMsg << (CUnsignedSyncCheckpoint)checkpoint;
321         checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
322
323         if (CSyncCheckpoint::strMasterPrivKey.empty())
324             return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
325         std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
326         CKey key;
327         key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
328         if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
329             return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
330
331         if(!checkpoint.ProcessSyncCheckpoint(NULL))
332         {
333             printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
334             return false;
335         }
336
337         // Relay checkpoint
338         {
339             LOCK(cs_vNodes);
340             BOOST_FOREACH(CNode* pnode, vNodes)
341                 checkpoint.RelayTo(pnode);
342         }
343         return true;
344     }
345
346     // Is the sync-checkpoint outside maturity window?
347     bool IsMatureSyncCheckpoint()
348     {
349         LOCK(cs_hashSyncCheckpoint);
350         // sync-checkpoint should always be accepted block
351         assert(mapBlockIndex.count(hashSyncCheckpoint));
352         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
353         return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
354                 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
355     }
356
357     // Is the sync-checkpoint too old?
358     bool IsSyncCheckpointTooOld(unsigned int nSeconds)
359     {
360         LOCK(cs_hashSyncCheckpoint);
361         // sync-checkpoint should always be accepted block
362         assert(mapBlockIndex.count(hashSyncCheckpoint));
363         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
364         return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
365     }
366 }
367
368 // ppcoin: sync-checkpoint master key
369 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
370
371 std::string CSyncCheckpoint::strMasterPrivKey = "";
372
373 // ppcoin: verify signature of sync-checkpoint message
374 bool CSyncCheckpoint::CheckSignature()
375 {
376     CKey key;
377     if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
378         return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
379     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
380         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
381
382     // Now unserialize the data
383     CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
384     sMsg >> *(CUnsignedSyncCheckpoint*)this;
385     return true;
386 }
387
388 // ppcoin: process synchronized checkpoint
389 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
390 {
391     if (!CheckSignature())
392         return false;
393
394     LOCK(Checkpoints::cs_hashSyncCheckpoint);
395     if (!mapBlockIndex.count(hashCheckpoint))
396     {
397         // We haven't received the checkpoint chain, keep the checkpoint as pending
398         Checkpoints::hashPendingCheckpoint = hashCheckpoint;
399         Checkpoints::checkpointMessagePending = *this;
400         printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
401         // Ask this guy to fill in what we're missing
402         if (pfrom)
403         {
404             pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
405             // ask directly as well in case rejected earlier by duplicate
406             // proof-of-stake because getblocks may not get it this time
407             pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
408         }
409         return false;
410     }
411
412     if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
413         return false;
414
415     CTxDB txdb;
416     CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
417     if (!pindexCheckpoint->IsInMainChain())
418     {
419         // checkpoint chain received but not yet main chain
420         CBlock block;
421         if (!block.ReadFromDisk(pindexCheckpoint))
422             return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
423         if (!block.SetBestChain(txdb, pindexCheckpoint))
424         {
425             Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
426             return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
427         }
428     }
429     txdb.Close();
430
431     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
432         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
433     Checkpoints::checkpointMessage = *this;
434     Checkpoints::hashPendingCheckpoint = 0;
435     Checkpoints::checkpointMessagePending.SetNull();
436     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
437     return true;
438 }