PPCoin: Synchronized checkpoint accepting descendant blocks only
[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, hashGenesisBlock )
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) return NULL;
47
48         int64 nResult;
49         BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
50         {
51             const uint256& hash = i.second;
52             std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
53             if (t != mapBlockIndex.end())
54                 return t->second;
55         }
56         return NULL;
57     }
58
59     // ppcoin: synchronized checkpoint (centrally broadcasted)
60     uint256 hashSyncCheckpoint;
61     CSyncCheckpoint checkpointMessage;
62     CSyncCheckpoint checkpointMessagePending;
63     CCriticalSection cs_hashSyncCheckpoint;
64
65     // ppcoin: only descendant of current sync-checkpoint is allowed
66     bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
67     {
68         if (!mapBlockIndex.count(hashSyncCheckpoint))
69             return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
70         if (!mapBlockIndex.count(hashCheckpoint))
71             return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
72
73         CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
74         CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
75         if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
76             return false;  // this is an older checkpoint, ignore
77
78         CBlockIndex* pindex = pindexCheckpointRecv;
79         while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
80             if (!(pindex = pindex->pprev))
81                 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
82         if (pindex->GetBlockHash() != hashSyncCheckpoint)
83             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
84         return true;
85     }
86
87     bool AcceptPendingSyncCheckpoint()
88     {
89         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
90             if ((!checkpointMessagePending.IsNull()) && mapBlockIndex.count(checkpointMessagePending.hashCheckpoint))
91             {
92                 if (!ValidateSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
93                 {
94                     checkpointMessagePending.SetNull();
95                     return false;
96                 }
97
98                 CTxDB txdb;
99                 if (!txdb.WriteSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
100                     return error("AcceptPendingSyncCheckpoint() : failed to write to db sync checkpoint %s\n", checkpointMessagePending.hashCheckpoint.ToString().c_str());
101                 txdb.Close();
102
103                 hashSyncCheckpoint = checkpointMessagePending.hashCheckpoint;
104                 checkpointMessage = checkpointMessagePending;
105                 checkpointMessagePending.SetNull();
106                 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
107                 // relay the checkpoint
108                 BOOST_FOREACH(CNode* pnode, vNodes)
109                     checkpointMessage.RelayTo(pnode);
110                 return true;
111             }
112
113         return false;
114     }
115
116     uint256 AutoSelectSyncCheckpoint()
117     {
118         // select block roughly 8 hours ago
119         CBlockIndex *pindex = mapBlockIndex[hashSyncCheckpoint];
120         while (pindex->pnext && pindex->pnext->GetBlockTime() + AUTO_CHECKPOINT_MIN_SPAN <= GetAdjustedTime())
121             pindex = pindex->pnext;
122         return pindex->GetBlockHash();
123     }
124
125     // Check against synchronized checkpoint
126     bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
127     {
128         if (fTestNet) return true; // Testnet has no checkpoints
129         int nHeight = pindexPrev->nHeight + 1;
130
131         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
132         {
133             // sync-checkpoint should always be accepted block
134             assert(mapBlockIndex.count(hashSyncCheckpoint));
135             const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
136
137             if (nHeight > pindexSync->nHeight)
138             {
139                 // trace back to same height as sync-checkpoint
140                 const CBlockIndex* pindex = pindexPrev;
141                 while (pindex->nHeight > pindexSync->nHeight)
142                     if (!(pindex = pindex->pprev))
143                         return error("CheckSync: pprev null - block index structure failure");
144                 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
145                     return false; // only descendant of sync-checkpoint can pass check
146             }
147             if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
148                 return false; // same height with sync-checkpoint
149             if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
150                 return false; // lower height than sync-checkpoint
151         }
152         return true;
153     }
154
155     // ppcoin: automatic checkpoint (represented by height of checkpoint)
156     int nAutoCheckpoint = 0;
157     int nBranchPoint = 0;    // branch point to alternative branch
158
159     // ppcoin: check automatic checkpoint
160     // To pass the check:
161     //   - All ancestors (including the block itself) have block index already
162     //   - The immediate ancestor in main chain must not have height less than
163     //     checkpoint height
164     bool CheckAuto(const CBlockIndex *pindex)
165     {
166         while (pindex)
167         {
168             if (pindex->IsInMainChain())
169             {
170                 if (pindex->nHeight >= nAutoCheckpoint)
171                     return true;
172                 else
173                 {
174                     nBranchPoint = pindex->nHeight;
175                     return error("Checkpoints: new block on alternative branch at height=%d before auto checkpoint at height=%d", pindex->nHeight, nAutoCheckpoint);
176                 }
177             }
178             else
179                 pindex = pindex->pprev;
180         }
181         return error("Checkpoints: failed to find any ancestor on main chain for the new block - internal error");
182     }
183
184     // ppcoin: get next chain checkpoint
185     int GetNextChainCheckpoint(const CBlockIndex *pindexLast)
186     {
187         CBigNum bnTarget;
188         CBigNum bnTargetMax = 0;  // max target of all blocks since checkpoint
189         CBigNum bnTargetMin = 0;  // min target of all candidate checkpoints
190         int nMinTargetHeight = 0; // min target height of candidate checkpoints
191         int nCheckpointMin = 0;   // minimum candidate checkpoint
192         int nCheckpointMax = 0;   // maximum candidate checkpoint
193         int nDepth = pindexLast->nHeight - pindexLast->nCheckpoint;
194         const CBlockIndex *pindex = pindexLast;
195         while (nDepth >= 0 && pindex)
196         {
197             bnTarget.SetCompact(pindex->nBits);
198             if (bnTarget > bnTargetMax)
199                 bnTargetMax = bnTarget;
200             if (nCheckpointMax > 0 && bnTarget < bnTargetMin)
201             {
202                 bnTargetMin = bnTarget;
203                 nMinTargetHeight = pindex->nHeight;
204             }
205             if (nCheckpointMax == 0 && pindexLast->GetBlockTime() - pindex->GetBlockTime() > AUTO_CHECKPOINT_MIN_SPAN)
206             {
207                 nCheckpointMax = pindex->nHeight;
208                 bnTargetMin.SetCompact(pindex->nBits);
209                 nMinTargetHeight = pindex->nHeight;
210             }
211             if (pindexLast->GetBlockTime() - pindex->GetBlockTime() < AUTO_CHECKPOINT_MAX_SPAN)
212                 nCheckpointMin = pindex->nHeight;
213             pindex = pindex->pprev;
214             nDepth--;
215         }
216
217         assert (nDepth == -1);  // arrive at chain checkpoint now
218
219         printf("Checkpoints: min=%d max=%d tminheight=%d tmin=0x%08x tmax=0x%08x\n",
220             nCheckpointMin, nCheckpointMax, nMinTargetHeight,
221             bnTargetMin.GetCompact(), bnTargetMax.GetCompact());
222         if (nCheckpointMax == 0) // checkpoint stays if max candidate not found
223             return pindexLast->nCheckpoint;
224
225         if (bnTargetMin * 100 > bnTargetMax * 90)
226             return nCheckpointMax;
227         if (bnTarget * 100 > bnTargetMax * 90)
228             return nMinTargetHeight;
229         else
230             return nCheckpointMin;
231     }
232
233     // ppcoin: get next auto checkpoint from the new chain checkpoint
234     int GetNextAutoCheckpoint(int nCheckpoint)
235     {
236         return (std::max(nAutoCheckpoint, nCheckpoint));
237     }
238
239     // ppcoin: advance to next automatic checkpoint
240     void AdvanceAutoCheckpoint(int nCheckpoint)
241     {
242         nAutoCheckpoint = GetNextAutoCheckpoint(nCheckpoint);
243         printf("Checkpoints: auto checkpoint now at height=%d\n", nAutoCheckpoint);
244     }
245
246     // ppcoin: reset auto checkpoint
247     bool ResetAutoCheckpoint(int nCheckpoint)
248     {
249         if (nCheckpoint <= 0 || nCheckpoint > nBestHeight)
250             return error("ResetAutoCheckpoint() : new checkpoint invalid");
251         if (nCheckpoint >= nAutoCheckpoint)
252             return error("ResetAutoCheckpoint() : new checkpoint not earlier than current auto checkpoint");
253         CTxDB txdb;
254         txdb.TxnBegin();
255         if (!txdb.WriteAutoCheckpoint(nCheckpoint, true))
256             return error("ResetAutoCheckpoint() : database write failed");
257         if (!txdb.TxnCommit())
258             return error("ResetAutoCheckpoint() : database commit failed");
259         nAutoCheckpoint = nCheckpoint;
260         nBranchPoint = 0;  // clear branch point
261
262         // clear ban list to accept alternative branches
263         CRITICAL_BLOCK(cs_vNodes)
264         {
265             BOOST_FOREACH(CNode* pnode, vNodes)
266                 pnode->ClearBanned();
267         }
268
269         return true;
270     }
271 }
272
273 // ppcoin: process synchronized checkpoint
274 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
275 {
276     if (!CheckSignature())
277         return false;
278
279     CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)
280     {
281         if (!mapBlockIndex.count(hashCheckpoint))
282         {
283             // We haven't accepted this block, keep the checkpoint as pending
284             Checkpoints::checkpointMessagePending = *this;
285             printf("ProcessSyncCheckpoint : pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
286             // Ask this guy to fill in what we're missing
287             if (pfrom)
288                 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
289             return false;
290         }
291         if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
292             return false;
293
294         CTxDB txdb;
295         if (!txdb.WriteSyncCheckpoint(this->hashCheckpoint))
296             return error("ProcessSyncCheckpoint() : failed to write to db sync checkpoint %s\n", this->hashCheckpoint.ToString().c_str());
297         txdb.Close();
298
299         Checkpoints::hashSyncCheckpoint = this->hashCheckpoint;
300         Checkpoints::checkpointMessage = *this;
301         Checkpoints::checkpointMessagePending.SetNull();
302         printf("ProcessSyncCheckpoint : sync-checkpoint at %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
303     }
304     return true;
305 }