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