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