PPCoin: Move CSyncCheckpoint class outside of Checkpoints namespace
[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             pindex = pindex->pprev;
81         if (pindex->GetBlockHash() != hashSyncCheckpoint)
82             return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
83         return true;
84     }
85
86     bool AcceptPendingSyncCheckpoint(uint256 hashAcceptedBlock)
87     {
88         if (!mapBlockIndex.count(hashAcceptedBlock))
89             return false;
90
91         CRITICAL_BLOCK(cs_hashSyncCheckpoint)
92             if ((!checkpointMessagePending.IsNull()) && checkpointMessagePending.hashCheckpoint == hashAcceptedBlock)
93             {
94                 if (!ValidateSyncCheckpoint(checkpointMessagePending.hashCheckpoint))
95                 {
96                     checkpointMessagePending.SetNull();
97                     return false;
98                 }
99                 hashSyncCheckpoint = checkpointMessagePending.hashCheckpoint;
100                 checkpointMessage = checkpointMessagePending;
101                 checkpointMessagePending.SetNull();
102                 return true;
103             }
104
105         return false;
106     }
107
108     // ppcoin: automatic checkpoint (represented by height of checkpoint)
109     int nAutoCheckpoint = 0;
110     int nBranchPoint = 0;    // branch point to alternative branch
111
112     // ppcoin: check automatic checkpoint
113     // To pass the check:
114     //   - All ancestors (including the block itself) have block index already
115     //   - The immediate ancestor in main chain must not have height less than
116     //     checkpoint height
117     bool CheckAuto(const CBlockIndex *pindex)
118     {
119         while (pindex)
120         {
121             if (pindex->IsInMainChain())
122             {
123                 if (pindex->nHeight >= nAutoCheckpoint)
124                     return true;
125                 else
126                 {
127                     nBranchPoint = pindex->nHeight;
128                     return error("Checkpoints: new block on alternative branch at height=%d before auto checkpoint at height=%d", pindex->nHeight, nAutoCheckpoint);
129                 }
130             }
131             else
132                 pindex = pindex->pprev;
133         }
134         return error("Checkpoints: failed to find any ancestor on main chain for the new block - internal error");
135     }
136
137     // ppcoin: get next chain checkpoint
138     int GetNextChainCheckpoint(const CBlockIndex *pindexLast)
139     {
140         CBigNum bnTarget;
141         CBigNum bnTargetMax = 0;  // max target of all blocks since checkpoint
142         CBigNum bnTargetMin = 0;  // min target of all candidate checkpoints
143         int nMinTargetHeight = 0; // min target height of candidate checkpoints
144         int nCheckpointMin = 0;   // minimum candidate checkpoint
145         int nCheckpointMax = 0;   // maximum candidate checkpoint
146         int nDepth = pindexLast->nHeight - pindexLast->nCheckpoint;
147         const CBlockIndex *pindex = pindexLast;
148         while (nDepth >= 0 && pindex)
149         {
150             bnTarget.SetCompact(pindex->nBits);
151             if (bnTarget > bnTargetMax)
152                 bnTargetMax = bnTarget;
153             if (nCheckpointMax > 0 && bnTarget < bnTargetMin)
154             {
155                 bnTargetMin = bnTarget;
156                 nMinTargetHeight = pindex->nHeight;
157             }
158             if (nCheckpointMax == 0 && pindexLast->GetBlockTime() - pindex->GetBlockTime() > AUTO_CHECKPOINT_MIN_SPAN)
159             {
160                 nCheckpointMax = pindex->nHeight;
161                 bnTargetMin.SetCompact(pindex->nBits);
162                 nMinTargetHeight = pindex->nHeight;
163             }
164             if (pindexLast->GetBlockTime() - pindex->GetBlockTime() < AUTO_CHECKPOINT_MAX_SPAN)
165                 nCheckpointMin = pindex->nHeight;
166             pindex = pindex->pprev;
167             nDepth--;
168         }
169
170         assert (nDepth == -1);  // arrive at chain checkpoint now
171
172         printf("Checkpoints: min=%d max=%d tminheight=%d tmin=0x%08x tmax=0x%08x\n",
173             nCheckpointMin, nCheckpointMax, nMinTargetHeight,
174             bnTargetMin.GetCompact(), bnTargetMax.GetCompact());
175         if (nCheckpointMax == 0) // checkpoint stays if max candidate not found
176             return pindexLast->nCheckpoint;
177
178         if (bnTargetMin * 100 > bnTargetMax * 90)
179             return nCheckpointMax;
180         if (bnTarget * 100 > bnTargetMax * 90)
181             return nMinTargetHeight;
182         else
183             return nCheckpointMin;
184     }
185
186     // ppcoin: get next auto checkpoint from the new chain checkpoint
187     int GetNextAutoCheckpoint(int nCheckpoint)
188     {
189         return (std::max(nAutoCheckpoint, nCheckpoint));
190     }
191
192     // ppcoin: advance to next automatic checkpoint
193     void AdvanceAutoCheckpoint(int nCheckpoint)
194     {
195         nAutoCheckpoint = GetNextAutoCheckpoint(nCheckpoint);
196         printf("Checkpoints: auto checkpoint now at height=%d\n", nAutoCheckpoint);
197     }
198
199     // ppcoin: reset auto checkpoint
200     bool ResetAutoCheckpoint(int nCheckpoint)
201     {
202         if (nCheckpoint <= 0 || nCheckpoint > nBestHeight)
203             return error("ResetAutoCheckpoint() : new checkpoint invalid");
204         if (nCheckpoint >= nAutoCheckpoint)
205             return error("ResetAutoCheckpoint() : new checkpoint not earlier than current auto checkpoint");
206         CTxDB txdb;
207         txdb.TxnBegin();
208         if (!txdb.WriteAutoCheckpoint(nCheckpoint, true))
209             return error("ResetAutoCheckpoint() : database write failed");
210         if (!txdb.TxnCommit())
211             return error("ResetAutoCheckpoint() : database commit failed");
212         nAutoCheckpoint = nCheckpoint;
213         nBranchPoint = 0;  // clear branch point
214
215         // clear ban list to accept alternative branches
216         CRITICAL_BLOCK(cs_vNodes)
217         {
218             BOOST_FOREACH(CNode* pnode, vNodes)
219                 pnode->ClearBanned();
220         }
221
222         return true;
223     }
224 }
225
226 // ppcoin: process synchronized checkpoint
227 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
228 {
229     if (!CheckSignature())
230         return false;
231
232     CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)
233     {
234         if (!mapBlockIndex.count(hashCheckpoint))
235         {
236             // We haven't accepted this block, keep the checkpoint as pending
237             Checkpoints::checkpointMessagePending = *this;
238             // Ask this guy to fill in what we're missing
239             if (pfrom)
240                 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
241             return false;
242         }
243         if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
244             return false;
245         Checkpoints::hashSyncCheckpoint = this->hashCheckpoint;
246         Checkpoints::checkpointMessage = *this;
247         Checkpoints::checkpointMessagePending.SetNull();
248     }
249     return true;
250 }