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