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 license.txt or http://www.opensource.org/licenses/mit-license.php.
8 #include <boost/version.hpp>
9 #include <boost/filesystem.hpp>
10 #include <boost/filesystem/fstream.hpp>
12 #include <leveldb/env.h>
13 #include <leveldb/cache.h>
14 #include <leveldb/filter_policy.h>
15 #include <memenv/memenv.h>
18 #include "checkpoints.h"
24 using namespace boost;
28 static leveldb::Options GetOptions() {
29 leveldb::Options options;
30 int nCacheSizeMB = GetArg("-dbcache", 25);
31 options.block_cache = leveldb::NewLRUCache(nCacheSizeMB * 1048576);
32 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
37 leveldb::Options options = GetOptions();
38 options.create_if_missing = true;
39 // This will leak but don't care here.
40 options.env = leveldb::NewMemEnv(leveldb::Env::Default());
41 leveldb::Status status = leveldb::DB::Open(options, "txdb", &txdb);
43 throw runtime_error(strprintf("Could not create mock LevelDB: %s", status.ToString().c_str()));
45 txdb.WriteVersion(CLIENT_VERSION);
48 // NOTE: CDB subclasses are created and destroyed VERY OFTEN. Therefore we have
49 // to keep databases in global variables to avoid constantly creating and
50 // destroying them, which sucks. In future the code should be changed to not
51 // treat the instantiation of a database as a free operation.
52 CTxDB::CTxDB(const char* pszMode)
57 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
63 filesystem::path directory = GetDataDir() / "txleveldb";
64 bool fCreate = strchr(pszMode, 'c');
66 options = GetOptions();
67 options.create_if_missing = fCreate;
68 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
69 filesystem::create_directory(directory);
70 printf("Opening LevelDB in %s\n", directory.string().c_str());
71 leveldb::Status status = leveldb::DB::Open(options, directory.string(), &txdb);
73 throw runtime_error(strprintf("CDB(): error opening database environment %s", status.ToString().c_str()));
77 if (fCreate && !Exists(string("version")))
79 bool fTmp = fReadOnly;
81 WriteVersion(CLIENT_VERSION);
84 printf("Opened LevelDB successfully\n");
91 delete options.filter_policy;
92 options.filter_policy = NULL;
93 delete options.block_cache;
94 options.block_cache = NULL;
99 bool CTxDB::TxnBegin()
101 assert(!activeBatch);
102 activeBatch = new leveldb::WriteBatch();
106 bool CTxDB::TxnCommit()
109 leveldb::Status status = pdb->Write(leveldb::WriteOptions(), activeBatch);
113 printf("LevelDB batch commit failure: %s\n", status.ToString().c_str());
119 class CBatchScanner : public leveldb::WriteBatch::Handler {
123 std::string *foundValue;
126 CBatchScanner() : foundEntry(false) {}
128 virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value) {
129 if (key.ToString() == needle) {
132 *foundValue = value.ToString();
136 virtual void Delete(const leveldb::Slice& key) {
137 if (key.ToString() == needle) {
144 // When performing a read, if we have an active batch we need to check it first
145 // before reading from the database, as the rest of the code assumes that once
146 // a database transaction begins reads are consistent with it. It would be good
147 // to change that assumption in future and avoid the performance hit, though in
148 // practice it does not appear to be large.
149 bool CTxDB::ScanBatch(const CDataStream &key, string *value, bool *deleted) const {
152 CBatchScanner scanner;
153 scanner.needle = key.str();
154 scanner.deleted = deleted;
155 scanner.foundValue = value;
156 leveldb::Status status = activeBatch->Iterate(&scanner);
158 throw runtime_error(status.ToString());
160 return scanner.foundEntry;
163 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
167 return Read(make_pair(string("tx"), hash), txindex);
170 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
173 return Write(make_pair(string("tx"), hash), txindex);
176 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
181 uint256 hash = tx.GetHash();
182 CTxIndex txindex(pos, tx.vout.size());
183 return Write(make_pair(string("tx"), hash), txindex);
186 bool CTxDB::EraseTxIndex(const CTransaction& tx)
189 uint256 hash = tx.GetHash();
191 return Erase(make_pair(string("tx"), hash));
194 bool CTxDB::ContainsTx(uint256 hash)
197 return Exists(make_pair(string("tx"), hash));
200 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
204 if (!ReadTxIndex(hash, txindex))
206 return (tx.ReadFromDisk(txindex.pos));
209 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
212 return ReadDiskTx(hash, tx, txindex);
215 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
217 return ReadDiskTx(outpoint.hash, tx, txindex);
220 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
223 return ReadDiskTx(outpoint.hash, tx, txindex);
226 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
228 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
231 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
233 return Read(string("hashBestChain"), hashBestChain);
236 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
238 return Write(string("hashBestChain"), hashBestChain);
241 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
243 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
246 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
248 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
251 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
253 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
256 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
258 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
261 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
263 return Read(string("strCheckpointPubKey"), strPubKey);
266 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
268 return Write(string("strCheckpointPubKey"), strPubKey);
271 static CBlockIndex *InsertBlockIndex(uint256 hash)
277 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
278 if (mi != mapBlockIndex.end())
282 CBlockIndex* pindexNew = new CBlockIndex();
284 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
285 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
286 pindexNew->phashBlock = &((*mi).first);
291 bool CTxDB::LoadBlockIndex()
293 if (mapBlockIndex.size() > 0) {
294 // Already loaded once in this session. It can happen during migration
298 // The block index is an in-memory structure that maps hashes to on-disk
299 // locations where the contents of the block can be found. Here, we scan it
300 // out of the DB and into mapBlockIndex.
301 leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
302 // Seek to start key.
303 CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
304 ssStartKey << make_pair(string("blockindex"), uint256(0));
305 iterator->Seek(ssStartKey.str());
306 // Now read each entry.
307 while (iterator->Valid())
309 // Unpack keys and values.
310 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
311 ssKey.write(iterator->key().data(), iterator->key().size());
312 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
313 ssValue.write(iterator->value().data(), iterator->value().size());
316 // Did we reach the end of the data to read?
317 if (fRequestShutdown || strType != "blockindex")
319 CDiskBlockIndex diskindex;
320 ssValue >> diskindex;
322 // Construct block index object
323 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
324 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
325 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
326 pindexNew->nFile = diskindex.nFile;
327 pindexNew->nBlockPos = diskindex.nBlockPos;
328 pindexNew->nHeight = diskindex.nHeight;
329 pindexNew->nMint = diskindex.nMint;
330 pindexNew->nMoneySupply = diskindex.nMoneySupply;
331 pindexNew->nFlags = diskindex.nFlags;
332 pindexNew->nStakeModifier = diskindex.nStakeModifier;
333 pindexNew->prevoutStake = diskindex.prevoutStake;
334 pindexNew->nStakeTime = diskindex.nStakeTime;
335 pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
336 pindexNew->nVersion = diskindex.nVersion;
337 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
338 pindexNew->nTime = diskindex.nTime;
339 pindexNew->nBits = diskindex.nBits;
340 pindexNew->nNonce = diskindex.nNonce;
342 // Watch for genesis block
343 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
344 pindexGenesisBlock = pindexNew;
346 if (!pindexNew->CheckIndex()) {
348 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
351 // NovaCoin: build setStakeSeen
352 if (pindexNew->IsProofOfStake())
353 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
359 if (fRequestShutdown)
362 // Calculate nChainTrust
363 vector<pair<int, CBlockIndex*> > vSortedByHeight;
364 vSortedByHeight.reserve(mapBlockIndex.size());
365 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
367 CBlockIndex* pindex = item.second;
368 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
370 sort(vSortedByHeight.begin(), vSortedByHeight.end());
371 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
373 CBlockIndex* pindex = item.second;
374 pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
375 // NovaCoin: calculate stake modifier checksum
376 pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
377 if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
378 return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
381 // Load hashBestChain pointer to end of best chain
382 if (!ReadHashBestChain(hashBestChain))
384 if (pindexGenesisBlock == NULL)
386 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
388 if (!mapBlockIndex.count(hashBestChain))
389 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
390 pindexBest = mapBlockIndex[hashBestChain];
391 nBestHeight = pindexBest->nHeight;
392 nBestChainTrust = pindexBest->nChainTrust;
394 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
395 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
396 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
398 // NovaCoin: load hashSyncCheckpoint
399 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
400 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
401 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
403 // Load bnBestInvalidTrust, OK if it doesn't exist
404 CBigNum bnBestInvalidTrust;
405 ReadBestInvalidTrust(bnBestInvalidTrust);
406 nBestInvalidTrust = bnBestInvalidTrust.getuint256();
408 // Verify blocks in the best chain
409 int nCheckLevel = GetArg("-checklevel", 1);
410 int nCheckDepth = GetArg( "-checkblocks", 2500);
411 if (nCheckDepth == 0)
412 nCheckDepth = 1000000000; // suffices until the year 19000
413 if (nCheckDepth > nBestHeight)
414 nCheckDepth = nBestHeight;
415 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
416 CBlockIndex* pindexFork = NULL;
417 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
418 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
420 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
423 if (!block.ReadFromDisk(pindex))
424 return error("LoadBlockIndex() : block.ReadFromDisk failed");
425 // check level 1: verify block validity
426 // check level 7: verify block signature too
427 if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
429 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
430 pindexFork = pindex->pprev;
432 // check level 2: verify transaction index validity
435 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
436 mapBlockPos[pos] = pindex;
437 BOOST_FOREACH(const CTransaction &tx, block.vtx)
439 uint256 hashTx = tx.GetHash();
441 if (ReadTxIndex(hashTx, txindex))
443 // check level 3: checker transaction hashes
444 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
446 // either an error or a duplicate transaction
447 CTransaction txFound;
448 if (!txFound.ReadFromDisk(txindex.pos))
450 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
451 pindexFork = pindex->pprev;
454 if (txFound.GetHash() != hashTx) // not a duplicate tx
456 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
457 pindexFork = pindex->pprev;
460 // check level 4: check whether spent txouts were spent within the main chain
461 unsigned int nOutput = 0;
464 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
468 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
469 if (!mapBlockPos.count(posFind))
471 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
472 pindexFork = pindex->pprev;
474 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
477 CTransaction txSpend;
478 if (!txSpend.ReadFromDisk(txpos))
480 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
481 pindexFork = pindex->pprev;
483 else if (!txSpend.CheckTransaction())
485 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
486 pindexFork = pindex->pprev;
491 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
492 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
496 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
497 pindexFork = pindex->pprev;
506 // check level 5: check whether all prevouts are marked spent
509 BOOST_FOREACH(const CTxIn &txin, tx.vin)
512 if (ReadTxIndex(txin.prevout.hash, txindex))
513 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
515 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
516 pindexFork = pindex->pprev;
523 if (pindexFork && !fRequestShutdown)
525 // Reorg back to the fork
526 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
528 if (!block.ReadFromDisk(pindexFork))
529 return error("LoadBlockIndex() : block.ReadFromDisk failed");
531 block.SetBestChain(txdb, pindexFork);