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;
26 leveldb::DB *txdb; // global pointer for LevelDB object instance
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);
36 // CDB subclasses are created and destroyed VERY OFTEN. That's why
37 // we shouldn't treat this as a free operations.
38 CTxDB::CTxDB(const char* pszMode)
42 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
50 filesystem::path directory = GetDataDir() / "txleveldb";
51 bool fCreate = strchr(pszMode, 'c');
53 options = GetOptions();
54 options.create_if_missing = fCreate;
55 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
56 filesystem::create_directory(directory);
57 printf("Opening LevelDB in %s\n", directory.string().c_str());
58 leveldb::Status status = leveldb::DB::Open(options, directory.string(), &txdb);
60 throw runtime_error(strprintf("CDB(): error opening database environment %s", status.ToString().c_str()));
64 if (Exists(string("version")))
66 ReadVersion(nVersion);
67 printf("Transaction index version is %d\n", nVersion);
71 bool fTmp = fReadOnly;
73 WriteVersion(DATABASE_VERSION);
77 printf("Opened LevelDB successfully\n");
84 delete options.filter_policy;
85 options.filter_policy = NULL;
86 delete options.block_cache;
87 options.block_cache = NULL;
92 bool CTxDB::TxnBegin()
95 activeBatch = new leveldb::WriteBatch();
99 bool CTxDB::TxnCommit()
102 leveldb::Status status = pdb->Write(leveldb::WriteOptions(), activeBatch);
106 printf("LevelDB batch commit failure: %s\n", status.ToString().c_str());
112 class CBatchScanner : public leveldb::WriteBatch::Handler {
116 std::string *foundValue;
119 CBatchScanner() : foundEntry(false) {}
121 virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value) {
122 if (key.ToString() == needle) {
125 *foundValue = value.ToString();
129 virtual void Delete(const leveldb::Slice& key) {
130 if (key.ToString() == needle) {
137 // When performing a read, if we have an active batch we need to check it first
138 // before reading from the database, as the rest of the code assumes that once
139 // a database transaction begins reads are consistent with it. It would be good
140 // to change that assumption in future and avoid the performance hit, though in
141 // practice it does not appear to be large.
142 bool CTxDB::ScanBatch(const CDataStream &key, string *value, bool *deleted) const {
145 CBatchScanner scanner;
146 scanner.needle = key.str();
147 scanner.deleted = deleted;
148 scanner.foundValue = value;
149 leveldb::Status status = activeBatch->Iterate(&scanner);
151 throw runtime_error(status.ToString());
153 return scanner.foundEntry;
156 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
160 return Read(make_pair(string("tx"), hash), txindex);
163 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
166 return Write(make_pair(string("tx"), hash), txindex);
169 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
174 uint256 hash = tx.GetHash();
175 CTxIndex txindex(pos, tx.vout.size());
176 return Write(make_pair(string("tx"), hash), txindex);
179 bool CTxDB::EraseTxIndex(const CTransaction& tx)
182 uint256 hash = tx.GetHash();
184 return Erase(make_pair(string("tx"), hash));
187 bool CTxDB::ContainsTx(uint256 hash)
190 return Exists(make_pair(string("tx"), hash));
193 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
197 if (!ReadTxIndex(hash, txindex))
199 return (tx.ReadFromDisk(txindex.pos));
202 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
205 return ReadDiskTx(hash, tx, txindex);
208 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
210 return ReadDiskTx(outpoint.hash, tx, txindex);
213 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
216 return ReadDiskTx(outpoint.hash, tx, txindex);
219 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
221 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
224 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
226 return Read(string("hashBestChain"), hashBestChain);
229 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
231 return Write(string("hashBestChain"), hashBestChain);
234 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
236 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
239 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
241 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
244 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
246 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
249 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
251 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
254 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
256 return Read(string("strCheckpointPubKey"), strPubKey);
259 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
261 return Write(string("strCheckpointPubKey"), strPubKey);
264 static CBlockIndex *InsertBlockIndex(uint256 hash)
270 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
271 if (mi != mapBlockIndex.end())
275 CBlockIndex* pindexNew = new CBlockIndex();
277 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
278 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
279 pindexNew->phashBlock = &((*mi).first);
284 bool CTxDB::LoadBlockIndex()
286 if (mapBlockIndex.size() > 0) {
287 // Already loaded once in this session. It can happen during migration
291 // The block index is an in-memory structure that maps hashes to on-disk
292 // locations where the contents of the block can be found. Here, we scan it
293 // out of the DB and into mapBlockIndex.
294 leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
295 // Seek to start key.
296 CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
297 ssStartKey << make_pair(string("blockindex"), uint256(0));
298 iterator->Seek(ssStartKey.str());
299 // Now read each entry.
300 while (iterator->Valid())
302 // Unpack keys and values.
303 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
304 ssKey.write(iterator->key().data(), iterator->key().size());
305 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
306 ssValue.write(iterator->value().data(), iterator->value().size());
309 // Did we reach the end of the data to read?
310 if (fRequestShutdown || strType != "blockindex")
312 CDiskBlockIndex diskindex;
313 ssValue >> diskindex;
315 uint256 blockHash = diskindex.GetBlockHash();
317 // Construct block index object
318 CBlockIndex* pindexNew = InsertBlockIndex(blockHash);
319 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
320 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
321 pindexNew->nFile = diskindex.nFile;
322 pindexNew->nBlockPos = diskindex.nBlockPos;
323 pindexNew->nHeight = diskindex.nHeight;
324 pindexNew->nMint = diskindex.nMint;
325 pindexNew->nMoneySupply = diskindex.nMoneySupply;
326 pindexNew->nFlags = diskindex.nFlags;
327 pindexNew->nStakeModifier = diskindex.nStakeModifier;
328 pindexNew->prevoutStake = diskindex.prevoutStake;
329 pindexNew->nStakeTime = diskindex.nStakeTime;
330 pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
331 pindexNew->nVersion = diskindex.nVersion;
332 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
333 pindexNew->nTime = diskindex.nTime;
334 pindexNew->nBits = diskindex.nBits;
335 pindexNew->nNonce = diskindex.nNonce;
337 // Watch for genesis block
338 if (pindexGenesisBlock == NULL && blockHash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
339 pindexGenesisBlock = pindexNew;
341 if (!pindexNew->CheckIndex()) {
343 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
346 // NovaCoin: build setStakeSeen
347 if (pindexNew->IsProofOfStake())
348 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
354 if (fRequestShutdown)
357 // Calculate nChainTrust
358 vector<pair<int, CBlockIndex*> > vSortedByHeight;
359 vSortedByHeight.reserve(mapBlockIndex.size());
360 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
362 CBlockIndex* pindex = item.second;
363 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
365 sort(vSortedByHeight.begin(), vSortedByHeight.end());
366 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
368 CBlockIndex* pindex = item.second;
369 pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
370 // NovaCoin: calculate stake modifier checksum
371 pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
372 if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
373 return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
376 // Load hashBestChain pointer to end of best chain
377 if (!ReadHashBestChain(hashBestChain))
379 if (pindexGenesisBlock == NULL)
381 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
383 if (!mapBlockIndex.count(hashBestChain))
384 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
385 pindexBest = mapBlockIndex[hashBestChain];
386 nBestHeight = pindexBest->nHeight;
387 nBestChainTrust = pindexBest->nChainTrust;
389 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
390 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
391 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
393 // NovaCoin: load hashSyncCheckpoint
394 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
395 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
396 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
398 // Load bnBestInvalidTrust, OK if it doesn't exist
399 CBigNum bnBestInvalidTrust;
400 ReadBestInvalidTrust(bnBestInvalidTrust);
401 nBestInvalidTrust = bnBestInvalidTrust.getuint256();
403 // Verify blocks in the best chain
404 int nCheckLevel = GetArg("-checklevel", 1);
405 int nCheckDepth = GetArg( "-checkblocks", 2500);
406 if (nCheckDepth == 0)
407 nCheckDepth = 1000000000; // suffices until the year 19000
408 if (nCheckDepth > nBestHeight)
409 nCheckDepth = nBestHeight;
410 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
411 CBlockIndex* pindexFork = NULL;
412 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
413 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
415 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
418 if (!block.ReadFromDisk(pindex))
419 return error("LoadBlockIndex() : block.ReadFromDisk failed");
420 // check level 1: verify block validity
421 // check level 7: verify block signature too
422 if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
424 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
425 pindexFork = pindex->pprev;
427 // check level 2: verify transaction index validity
430 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
431 mapBlockPos[pos] = pindex;
432 BOOST_FOREACH(const CTransaction &tx, block.vtx)
434 uint256 hashTx = tx.GetHash();
436 if (ReadTxIndex(hashTx, txindex))
438 // check level 3: checker transaction hashes
439 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
441 // either an error or a duplicate transaction
442 CTransaction txFound;
443 if (!txFound.ReadFromDisk(txindex.pos))
445 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
446 pindexFork = pindex->pprev;
449 if (txFound.GetHash() != hashTx) // not a duplicate tx
451 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
452 pindexFork = pindex->pprev;
455 // check level 4: check whether spent txouts were spent within the main chain
456 unsigned int nOutput = 0;
459 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
463 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
464 if (!mapBlockPos.count(posFind))
466 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
467 pindexFork = pindex->pprev;
469 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
472 CTransaction txSpend;
473 if (!txSpend.ReadFromDisk(txpos))
475 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
476 pindexFork = pindex->pprev;
478 else if (!txSpend.CheckTransaction())
480 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
481 pindexFork = pindex->pprev;
486 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
487 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
491 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
492 pindexFork = pindex->pprev;
501 // check level 5: check whether all prevouts are marked spent
504 BOOST_FOREACH(const CTxIn &txin, tx.vin)
507 if (ReadTxIndex(txin.prevout.hash, txindex))
508 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
510 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
511 pindexFork = pindex->pprev;
518 if (pindexFork && !fRequestShutdown)
520 // Reorg back to the fork
521 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
523 if (!block.ReadFromDisk(pindexFork))
524 return error("LoadBlockIndex() : block.ReadFromDisk failed");
526 block.SetBestChain(txdb, pindexFork);