PPCoin: Fix a startup issue loading blkindex since 90f58617
[novacoin.git] / src / checkpoints.cpp
1 // Copyright (c) 2011 The Bitcoin developers
2 // Copyright (c) 2011-2012 The PPCoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5
6 #include <boost/assign/list_of.hpp> // for 'map_list_of()'
7 #include <boost/foreach.hpp>
8
9 #include "headers.h"
10 #include "checkpoints.h"
11
12 namespace Checkpoints
13 {
14     typedef std::map<int, uint256> MapCheckpoints;   // hardened checkpoints
15
16     //
17     // What makes a good checkpoint block?
18     // + Is surrounded by blocks with reasonable timestamps
19     //   (no blocks before with a timestamp after, none after with
20     //    timestamp before)
21     // + Contains no strange transactions
22     //
23     static MapCheckpoints mapCheckpoints =
24         boost::assign::map_list_of
25         ( 0, hashGenesisBlockOfficial )
26         ; // ppcoin: no checkpoint yet; to be created in future releases
27
28     bool CheckHardened(int nHeight, const uint256& hash)
29     {
30         if (fTestNet) return true; // Testnet has no checkpoints
31
32         MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
33         if (i == mapCheckpoints.end()) return true;
34         return hash == i->second;
35     }
36
37     int GetTotalBlocksEstimate()
38     {
39         if (fTestNet) return 0;
40
41         return mapCheckpoints.rbegin()->first;
42     }
43
44     CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
45     {
46         if (fTestNet) {
47             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hashGenesisBlock);
48             if (t != mapBlockIndex.end())
49                 return t->second;
50             return NULL;
51         }
52
53         int64 nResult;
54         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
55         {
56             const uint256& hash = i.second;
57             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
58             if (t != mapBlockIndex.end())
59                 return t->second;
60         }
61         return NULL;
62     }
63
64     // ppcoin: synchronized checkpoint (centrally broadcasted)
65     uint256 hashSyncCheckpoint = 0;
66     uint256 hashPendingCheckpoint = 0;
67     CSyncCheckpoint checkpointMessage;
68     CSyncCheckpoint checkpointMessagePending;
69     uint256 hashInvalidCheckpoint = 0;
70     CCriticalSection cs_hashSyncCheckpoint;
71
72     // ppcoin: get last synchronized checkpoint
73     CBlockIndex* GetLastSyncCheckpoint()
74     {
75         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
76         {
77             if (!mapBlockIndex.count(hashSyncCheckpoint))
78                 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
79             else
80                 return mapBlockIndex[hashSyncCheckpoint];
81         }
82         return NULL;
83     }
84
85     // ppcoin: only descendant of current sync-checkpoint is allowed
86     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
87     {
88         if (!mapBlockIndex.count(hashSyncCheckpoint))
89             return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
90         if (!mapBlockIndex.count(hashCheckpoint))
91             return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
92
93         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
94         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
95
96         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
97         {
98             // Received an older checkpoint, trace back from current checkpoint
99             // to the same height of the received checkpoint to verify
100             // that current checkpoint should be a descendant block
101             CBlockIndex* pindex = pindexSyncCheckpoint;
102             while (pindex->nHeight > pindexCheckpointRecv->nHeight)
103                 if (!(pindex = pindex->pprev))
104                     return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
105             if (pindex->GetBlockHash() != hashCheckpoint)
106             {
107                 hashInvalidCheckpoint = hashCheckpoint;
108                 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
109             }
110             return false; // ignore older checkpoint
111         }
112
113         // Received checkpoint should be a descendant block of the current
114         // checkpoint. Trace back to the same height of current checkpoint
115         // to verify.
116         CBlockIndex* pindex = pindexCheckpointRecv;
117         while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
118             if (!(pindex = pindex->pprev))
119                 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
120         if (pindex->GetBlockHash() != hashSyncCheckpoint)
121         {
122             hashInvalidCheckpoint = hashCheckpoint;
123             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
124         }
125         return true;
126     }
127
128     bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
129     {
130         CTxDB txdb;
131         txdb.TxnBegin();
132         if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
133         {
134             txdb.TxnAbort();
135             return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
136         }
137         if (!txdb.TxnCommit())
138             return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
139         txdb.Close();
140
141         Checkpoints::hashSyncCheckpoint = hashCheckpoint;
142         return true;
143     }
144
145     bool AcceptPendingSyncCheckpoint()
146     {
147         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
148         {
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                     txdb.TxnBegin();
163                     if (!Reorganize(txdb, pindexCheckpoint))
164                     {
165                         txdb.TxnAbort();
166                         hashInvalidCheckpoint = hashPendingCheckpoint;
167                         return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
168                     }
169                 }
170                 txdb.Close();
171
172                 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
173                     return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
174                 hashPendingCheckpoint = 0;
175                 checkpointMessage = checkpointMessagePending;
176                 checkpointMessagePending.SetNull();
177                 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
178                 // relay the checkpoint
179                 if (!checkpointMessage.IsNull())
180                     BOOST_FOREACH(CNode* pnode, vNodes)
181                         checkpointMessage.RelayTo(pnode);
182                 return true;
183             }
184         }
185
186         return false;
187     }
188
189     uint256 AutoSelectSyncCheckpoint()
190     {
191         // select block roughly 8 hours ago
192         CBlockIndex *pindex = mapBlockIndex[hashSyncCheckpoint];
193         while (pindex->pnext && pindex->pnext->GetBlockTime() + AUTO_CHECKPOINT_MIN_SPAN <= GetAdjustedTime())
194             pindex = pindex->pnext;
195         return pindex->GetBlockHash();
196     }
197
198     // Check against synchronized checkpoint
199     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
200     {
201         if (fTestNet) return true; // Testnet has no checkpoints
202         int nHeight = pindexPrev->nHeight + 1;
203
204         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
205         {
206             // sync-checkpoint should always be accepted block
207             assert(mapBlockIndex.count(hashSyncCheckpoint));
208             const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
209
210             if (nHeight > pindexSync->nHeight)
211             {
212                 // trace back to same height as sync-checkpoint
213                 const CBlockIndex* pindex = pindexPrev;
214                 while (pindex->nHeight > pindexSync->nHeight)
215                     if (!(pindex = pindex->pprev))
216                         return error("CheckSync: pprev null - block index structure failure");
217                 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
218                     return false; // only descendant of sync-checkpoint can pass check
219             }
220             if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
221                 return false; // same height with sync-checkpoint
222             if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
223                 return false; // lower height than sync-checkpoint
224         }
225         return true;
226     }
227
228     bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
229     {
230         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
231         {
232             if (hashPendingCheckpoint == 0)
233                 return false;
234             if (hashBlock == hashPendingCheckpoint)
235                 return true;
236             if (mapOrphanBlocks.count(hashPendingCheckpoint) 
237                 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
238                 return true;
239         }
240         return false;
241     }
242
243     // ppcoin: reset synchronized checkpoint to last hardened checkpoint
244     bool ResetSyncCheckpoint()
245     {
246         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
247         {
248             const uint256& hash = mapCheckpoints.rbegin()->second;
249             if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
250             {
251                 // checkpoint block accepted but not yet in main chain
252                 printf("ResetSyncCheckpoint: Reorganize to hardened checkpoint %s\n", hash.ToString().c_str());
253                 CTxDB txdb;
254                 txdb.TxnBegin();
255                 if (!Reorganize(txdb, mapBlockIndex[hash]))
256                 {
257                     txdb.TxnAbort();
258                     return error("ResetSyncCheckpoint: Reorganize failed for hardened checkpoint %s", hash.ToString().c_str());
259                 }
260                 txdb.Close();
261             }
262             else if(!mapBlockIndex.count(hash))
263             {
264                 // checkpoint block not yet accepted
265                 hashPendingCheckpoint = hash;
266                 checkpointMessagePending.SetNull();
267                 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
268                 // TODO: when to ask for the checkpoint chain?
269             }
270
271             BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
272             {
273                 const uint256& hash = i.second;
274                 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
275                 {
276                     if (!WriteSyncCheckpoint(hash))
277                         return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
278                     printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
279                     return true;
280                 }
281             }
282
283             return false;
284         }
285     }
286 }
287
288 // ppcoin: sync-checkpoint master key
289 const std::string CSyncCheckpoint::strMasterPubKey = "0424f20205e5da98ba632bbd278a11a6499585f62bfb2c782377ef59f0251daab8085fc31471bcb8180bc75ed0fa41bb50c7c084511d54015a3a5241d645c7268a";
290
291 // ppcoin: verify signature of sync-checkpoint message
292 bool CSyncCheckpoint::CheckSignature()
293 {
294     CKey key;
295     if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
296         return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
297     if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
298         return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
299
300     // Now unserialize the data
301     CDataStream sMsg(vchMsg);
302     sMsg >> *(CUnsignedSyncCheckpoint*)this;
303     return true;
304 }
305
306 // ppcoin: process synchronized checkpoint
307 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
308 {
309     if (!CheckSignature())
310         return false;
311
312     CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)
313     {
314         if (!mapBlockIndex.count(hashCheckpoint))
315         {
316             // We haven't received the checkpoint chain, keep the checkpoint as pending
317             Checkpoints::hashPendingCheckpoint = hashCheckpoint;
318             Checkpoints::checkpointMessagePending = *this;
319             printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
320             // Ask this guy to fill in what we're missing
321             if (pfrom)
322             {
323                 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
324                 // ask directly as well in case rejected earlier by duplicate
325                 // proof-of-stake because getblocks may not get it this time
326                 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
327             }
328             return false;
329         }
330
331         if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
332             return false;
333
334         CTxDB txdb;
335         CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
336         if (!pindexCheckpoint->IsInMainChain())
337         {
338             // checkpoint chain received but not yet main chain
339             txdb.TxnBegin();
340             if (!Reorganize(txdb, pindexCheckpoint))
341             {
342                 txdb.TxnAbort();
343                 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
344                 return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
345             }
346         }
347         txdb.Close();
348
349         if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
350             return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
351         Checkpoints::checkpointMessage = *this;
352         Checkpoints::hashPendingCheckpoint = 0;
353         Checkpoints::checkpointMessagePending.SetNull();
354         printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
355     }
356     return true;
357 }