Update to 0.3.0 (New upstream + new RPC calls)
[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         ;
31
32     bool CheckHardened(int nHeight, const uint256& hash)
33     {
34         if (fTestNet) return true; // Testnet has no checkpoints
35
36         MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
37         if (i == mapCheckpoints.end()) return true;
38         return hash == i->second;
39     }
40
41     int GetTotalBlocksEstimate()
42     {
43         if (fTestNet) return 0;
44
45         return mapCheckpoints.rbegin()->first;
46     }
47
48     CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
49     {
50         if (fTestNet) {
51             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hashGenesisBlock);
52             if (t != mapBlockIndex.end())
53                 return t->second;
54             return NULL;
55         }
56
57         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
58         {
59             const uint256& hash = i.second;
60             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
61             if (t != mapBlockIndex.end())
62                 return t->second;
63         }
64         return NULL;
65     }
66
67     // ppcoin: synchronized checkpoint (centrally broadcasted)
68     uint256 hashSyncCheckpoint = 0;
69     uint256 hashPendingCheckpoint = 0;
70     CSyncCheckpoint checkpointMessage;
71     CSyncCheckpoint checkpointMessagePending;
72     uint256 hashInvalidCheckpoint = 0;
73     CCriticalSection cs_hashSyncCheckpoint;
74
75     // ppcoin: get last synchronized checkpoint
76     CBlockIndex* GetLastSyncCheckpoint()
77     {
78         LOCK(cs_hashSyncCheckpoint);
79         if (!mapBlockIndex.count(hashSyncCheckpoint))
80             error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
81         else
82             return mapBlockIndex[hashSyncCheckpoint];
83         return NULL;
84     }
85
86     // ppcoin: only descendant of current sync-checkpoint is allowed
87     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
88     {
89         if (!mapBlockIndex.count(hashSyncCheckpoint))
90             return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
91         if (!mapBlockIndex.count(hashCheckpoint))
92             return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
93
94         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
95         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
96
97         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
98         {
99             // Received an older checkpoint, trace back from current checkpoint
100             // to the same height of the received checkpoint to verify
101             // that current checkpoint should be a descendant block
102             CBlockIndex* pindex = pindexSyncCheckpoint;
103             while (pindex->nHeight > pindexCheckpointRecv->nHeight)
104                 if (!(pindex = pindex->pprev))
105                     return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
106             if (pindex->GetBlockHash() != hashCheckpoint)
107             {
108                 hashInvalidCheckpoint = hashCheckpoint;
109                 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
110             }
111             return false; // ignore older checkpoint
112         }
113
114         // Received checkpoint should be a descendant block of the current
115         // checkpoint. Trace back to the same height of current checkpoint
116         // to verify.
117         CBlockIndex* pindex = pindexCheckpointRecv;
118         while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
119             if (!(pindex = pindex->pprev))
120                 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
121         if (pindex->GetBlockHash() != hashSyncCheckpoint)
122         {
123             hashInvalidCheckpoint = hashCheckpoint;
124             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
125         }
126         return true;
127     }
128
129     bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
130     {
131         CTxDB txdb;
132         txdb.TxnBegin();
133         if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
134         {
135             txdb.TxnAbort();
136             return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
137         }
138         if (!txdb.TxnCommit())
139             return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
140         txdb.Close();
141
142         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
143         return true;
144     }
145
146     bool AcceptPendingSyncCheckpoint()
147     {
148         LOCK(cs_hashSyncCheckpoint);
149         if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
150         {
151             if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
152             {
153                 hashPendingCheckpoint = 0;
154                 checkpointMessagePending.SetNull();
155                 return false;
156             }
157
158             CTxDB txdb;
159             CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
160             if (!pindexCheckpoint->IsInMainChain())
161             {
162                 CBlock block;
163                 if (!block.ReadFromDisk(pindexCheckpoint))
164                     return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
165                 if (!block.SetBestChain(txdb, pindexCheckpoint))
166                 {
167                     hashInvalidCheckpoint = hashPendingCheckpoint;
168                     return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
169                 }
170             }
171             txdb.Close();
172
173             if (!WriteSyncCheckpoint(hashPendingCheckpoint))
174                 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
175             hashPendingCheckpoint = 0;
176             checkpointMessage = checkpointMessagePending;
177             checkpointMessagePending.SetNull();
178             printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
179             // relay the checkpoint
180             if (!checkpointMessage.IsNull())
181             {
182                 BOOST_FOREACH(CNode* pnode, vNodes)
183                     checkpointMessage.RelayTo(pnode);
184             }
185             return true;
186         }
187         return false;
188     }
189
190     // Automatically select a suitable sync-checkpoint 
191     uint256 AutoSelectSyncCheckpoint()
192     {
193         // Proof-of-work blocks are immediately checkpointed
194         // to defend against 51% attack which rejects other miners block 
195
196         // Select the last proof-of-work block
197         const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
198         // Search forward for a block within max span and maturity window
199         while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
200             pindex = pindex->pnext;
201         return pindex->GetBlockHash();
202     }
203
204     // Check against synchronized checkpoint
205     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
206     {
207         if (fTestNet) return true; // Testnet has no checkpoints
208         int nHeight = pindexPrev->nHeight + 1;
209
210         LOCK(cs_hashSyncCheckpoint);
211         // sync-checkpoint should always be accepted block
212         assert(mapBlockIndex.count(hashSyncCheckpoint));
213         const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
214
215         if (nHeight > pindexSync->nHeight)
216         {
217             // trace back to same height as sync-checkpoint
218             const CBlockIndex* pindex = pindexPrev;
219             while (pindex->nHeight > pindexSync->nHeight)
220                 if (!(pindex = pindex->pprev))
221                     return error("CheckSync: pprev null - block index structure failure");
222             if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
223                 return false; // only descendant of sync-checkpoint can pass check
224         }
225         if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
226             return false; // same height with sync-checkpoint
227         if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
228             return false; // lower height than sync-checkpoint
229         return true;
230     }
231
232     bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
233     {
234         LOCK(cs_hashSyncCheckpoint);
235         if (hashPendingCheckpoint == 0)
236             return false;
237         if (hashBlock == hashPendingCheckpoint)
238             return true;
239         if (mapOrphanBlocks.count(hashPendingCheckpoint) 
240             && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
241             return true;
242         return false;
243     }
244
245     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
246     bool ResetSyncCheckpoint()
247     {
248         LOCK(cs_hashSyncCheckpoint);
249         const uint256& hash = mapCheckpoints.rbegin()->second;
250         if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
251         {
252             // checkpoint block accepted but not yet in main chain
253             printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
254             CTxDB txdb;
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 (!block.SetBestChain(txdb, mapBlockIndex[hash]))
259             {
260                 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
261             }
262             txdb.Close();
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;
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 = hashGenesisBlock;
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     CTxDB txdb;
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(txdb, pindexCheckpoint))
423         {
424             Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
425             return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
426         }
427     }
428     txdb.Close();
429
430     if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
431         return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
432     Checkpoints::checkpointMessage = *this;
433     Checkpoints::hashPendingCheckpoint = 0;
434     Checkpoints::checkpointMessagePending.SetNull();
435     printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
436     return true;
437 }