1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 #include "checkpoints.h"
12 #include <boost/version.hpp>
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
21 using namespace boost;
24 // In practice this won't do anything because the test framework always initializes
25 // an in-memory BDB via bitdb.MakeMock() first, as we use BDB for addresses and wallets.
34 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
38 return Read(make_pair(string("tx"), hash), txindex);
41 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
44 return Write(make_pair(string("tx"), hash), txindex);
47 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
52 uint256 hash = tx.GetHash();
53 CTxIndex txindex(pos, tx.vout.size());
54 return Write(make_pair(string("tx"), hash), txindex);
57 bool CTxDB::EraseTxIndex(const CTransaction& tx)
60 uint256 hash = tx.GetHash();
62 return Erase(make_pair(string("tx"), hash));
65 bool CTxDB::ContainsTx(uint256 hash)
68 return Exists(make_pair(string("tx"), hash));
71 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
75 if (!ReadTxIndex(hash, txindex))
77 return (tx.ReadFromDisk(txindex.pos));
80 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
83 return ReadDiskTx(hash, tx, txindex);
86 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
88 return ReadDiskTx(outpoint.hash, tx, txindex);
91 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
94 return ReadDiskTx(outpoint.hash, tx, txindex);
97 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
99 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
102 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
104 return Read(string("hashBestChain"), hashBestChain);
107 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
109 return Write(string("hashBestChain"), hashBestChain);
112 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
114 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
117 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
119 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
122 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
124 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
127 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
129 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
132 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
134 return Read(string("strCheckpointPubKey"), strPubKey);
137 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
139 return Write(string("strCheckpointPubKey"), strPubKey);
142 bool CTxDB::ReadModifierUpgradeTime(unsigned int& nUpgradeTime)
144 return Read(string("nUpgradeTime"), nUpgradeTime);
147 bool CTxDB::WriteModifierUpgradeTime(const unsigned int& nUpgradeTime)
149 return Write(string("nUpgradeTime"), nUpgradeTime);
152 CBlockIndex static * InsertBlockIndex(uint256 hash)
158 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
159 if (mi != mapBlockIndex.end())
163 CBlockIndex* pindexNew = new CBlockIndex();
165 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
166 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
167 pindexNew->phashBlock = &((*mi).first);
172 bool CTxDB::LoadBlockIndex()
174 if (!LoadBlockIndexGuts())
177 if (fRequestShutdown)
180 // Calculate nChainTrust
181 vector<pair<int, CBlockIndex*> > vSortedByHeight;
182 vSortedByHeight.reserve(mapBlockIndex.size());
183 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
185 CBlockIndex* pindex = item.second;
186 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
188 sort(vSortedByHeight.begin(), vSortedByHeight.end());
189 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
191 CBlockIndex* pindex = item.second;
192 pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
193 // ppcoin: calculate stake modifier checksum
194 pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
195 if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
196 return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
199 // Load hashBestChain pointer to end of best chain
200 if (!ReadHashBestChain(hashBestChain))
202 if (pindexGenesisBlock == NULL)
204 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
206 if (!mapBlockIndex.count(hashBestChain))
207 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
208 pindexBest = mapBlockIndex[hashBestChain];
209 nBestHeight = pindexBest->nHeight;
210 nBestChainTrust = pindexBest->nChainTrust;
211 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
212 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
213 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
215 // ppcoin: load hashSyncCheckpoint
216 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
217 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
218 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
220 // Load bnBestInvalidTrust, OK if it doesn't exist
221 CBigNum bnBestInvalidTrust;
222 ReadBestInvalidTrust(bnBestInvalidTrust);
223 nBestInvalidTrust = bnBestInvalidTrust.getuint256();
225 // Verify blocks in the best chain
226 int nCheckLevel = GetArg("-checklevel", 1);
227 int nCheckDepth = GetArg( "-checkblocks", 2500);
228 if (nCheckDepth == 0)
229 nCheckDepth = 1000000000; // suffices until the year 19000
230 if (nCheckDepth > nBestHeight)
231 nCheckDepth = nBestHeight;
232 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
233 CBlockIndex* pindexFork = NULL;
234 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
235 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
237 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
240 if (!block.ReadFromDisk(pindex))
241 return error("LoadBlockIndex() : block.ReadFromDisk failed");
242 // check level 1: verify block validity
243 // check level 7: verify block signature too
244 if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
246 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
247 pindexFork = pindex->pprev;
249 // check level 2: verify transaction index validity
252 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
253 mapBlockPos[pos] = pindex;
254 BOOST_FOREACH(const CTransaction &tx, block.vtx)
256 uint256 hashTx = tx.GetHash();
258 if (ReadTxIndex(hashTx, txindex))
260 // check level 3: checker transaction hashes
261 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
263 // either an error or a duplicate transaction
264 CTransaction txFound;
265 if (!txFound.ReadFromDisk(txindex.pos))
267 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
268 pindexFork = pindex->pprev;
271 if (txFound.GetHash() != hashTx) // not a duplicate tx
273 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
274 pindexFork = pindex->pprev;
277 // check level 4: check whether spent txouts were spent within the main chain
278 unsigned int nOutput = 0;
281 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
285 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
286 if (!mapBlockPos.count(posFind))
288 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
289 pindexFork = pindex->pprev;
291 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
294 CTransaction txSpend;
295 if (!txSpend.ReadFromDisk(txpos))
297 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
298 pindexFork = pindex->pprev;
300 else if (!txSpend.CheckTransaction())
302 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
303 pindexFork = pindex->pprev;
308 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
309 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
313 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
314 pindexFork = pindex->pprev;
323 // check level 5: check whether all prevouts are marked spent
326 BOOST_FOREACH(const CTxIn &txin, tx.vin)
329 if (ReadTxIndex(txin.prevout.hash, txindex))
330 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
332 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
333 pindexFork = pindex->pprev;
340 if (pindexFork && !fRequestShutdown)
342 // Reorg back to the fork
343 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
345 if (!block.ReadFromDisk(pindexFork))
346 return error("LoadBlockIndex() : block.ReadFromDisk failed");
348 block.SetBestChain(txdb, pindexFork);
356 bool CTxDB::LoadBlockIndexGuts()
358 // Get database cursor
359 Dbc* pcursor = GetCursor();
363 // Load mapBlockIndex
364 unsigned int fFlags = DB_SET_RANGE;
368 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
369 if (fFlags == DB_SET_RANGE)
370 ssKey << make_pair(string("blockindex"), uint256(0));
371 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
372 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
374 if (ret == DB_NOTFOUND)
384 if (strType == "blockindex" && !fRequestShutdown)
386 CDiskBlockIndex diskindex;
387 ssValue >> diskindex;
389 uint256 blockHash = diskindex.GetBlockHash();
391 // Construct block index object
392 CBlockIndex* pindexNew = InsertBlockIndex(blockHash);
393 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
394 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
395 pindexNew->nFile = diskindex.nFile;
396 pindexNew->nBlockPos = diskindex.nBlockPos;
397 pindexNew->nHeight = diskindex.nHeight;
398 pindexNew->nMint = diskindex.nMint;
399 pindexNew->nMoneySupply = diskindex.nMoneySupply;
400 pindexNew->nFlags = diskindex.nFlags;
401 pindexNew->nStakeModifier = diskindex.nStakeModifier;
402 pindexNew->prevoutStake = diskindex.prevoutStake;
403 pindexNew->nStakeTime = diskindex.nStakeTime;
404 pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
405 pindexNew->nVersion = diskindex.nVersion;
406 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
407 pindexNew->nTime = diskindex.nTime;
408 pindexNew->nBits = diskindex.nBits;
409 pindexNew->nNonce = diskindex.nNonce;
411 // Watch for genesis block
412 if (pindexGenesisBlock == NULL && blockHash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
413 pindexGenesisBlock = pindexNew;
415 if (!pindexNew->CheckIndex())
416 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
418 // ppcoin: build setStakeSeen
419 if (pindexNew->IsProofOfStake())
420 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
424 break; // if shutdown requested or finished loading block index
427 catch (std::exception &e) {
428 return error("%s() : deserialize error", __PRETTY_FUNCTION__);