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