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