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