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"
19 #include "txdb-leveldb.h"
25 leveldb::DB *txdb; // global pointer for LevelDB object instance
27 static leveldb::Options GetOptions() {
28 leveldb::Options options;
29 int nCacheSizeMB = GetArgInt("-dbcache", 25);
30 options.block_cache = leveldb::NewLRUCache(nCacheSizeMB * 1048576);
31 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
35 void init_blockindex(leveldb::Options& options, bool fRemoveOld = false) {
37 boost::filesystem::path directory = GetDataDir() / "txleveldb";
40 boost::filesystem::remove_all(directory); // remove directory
41 unsigned int nFile = 1;
45 boost::filesystem::path strBlockFile = GetDataDir() / strprintf("blk%04u.dat", nFile);
47 // Break if no such file
48 if( !boost::filesystem::exists( strBlockFile ) )
51 boost::filesystem::remove(strBlockFile);
57 boost::filesystem::create_directory(directory);
58 printf("Opening LevelDB in %s\n", directory.string().c_str());
59 leveldb::Status status = leveldb::DB::Open(options, directory.string(), &txdb);
61 throw runtime_error(strprintf("init_blockindex(): error opening database environment %s", status.ToString().c_str()));
65 // CDB subclasses are created and destroyed VERY OFTEN. That's why
66 // we shouldn't treat this as free operations.
67 CTxDB::CTxDB(const char* pszMode)
71 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
78 bool fCreate = strchr(pszMode, 'c');
80 options = GetOptions();
81 options.create_if_missing = fCreate;
82 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
84 init_blockindex(options); // Init directory
87 if (Exists(string("version")))
89 ReadVersion(nVersion);
90 printf("Transaction index version is %d\n", nVersion);
92 if (nVersion < DATABASE_VERSION)
94 printf("Required index version is %d, removing old database\n", DATABASE_VERSION);
96 // Leveldb instance destruction
102 init_blockindex(options, true); // Remove directory and create new database
105 bool fTmp = fReadOnly;
107 WriteVersion(DATABASE_VERSION); // Save transaction index version
113 bool fTmp = fReadOnly;
115 WriteVersion(DATABASE_VERSION);
119 printf("Opened LevelDB successfully\n");
126 delete options.filter_policy;
127 options.filter_policy = NULL;
128 delete options.block_cache;
129 options.block_cache = NULL;
134 bool CTxDB::TxnBegin()
136 assert(!activeBatch);
137 activeBatch = new leveldb::WriteBatch();
141 bool CTxDB::TxnCommit()
144 leveldb::Status status = pdb->Write(leveldb::WriteOptions(), activeBatch);
148 printf("LevelDB batch commit failure: %s\n", status.ToString().c_str());
154 class CBatchScanner : public leveldb::WriteBatch::Handler {
158 std::string *foundValue;
161 CBatchScanner() : foundEntry(false) {}
163 virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value) {
164 if (key.ToString() == needle) {
167 *foundValue = value.ToString();
171 virtual void Delete(const leveldb::Slice& key) {
172 if (key.ToString() == needle) {
179 // When performing a read, if we have an active batch we need to check it first
180 // before reading from the database, as the rest of the code assumes that once
181 // a database transaction begins reads are consistent with it. It would be good
182 // to change that assumption in future and avoid the performance hit, though in
183 // practice it does not appear to be large.
184 bool CTxDB::ScanBatch(const CDataStream &key, string *value, bool *deleted) const {
187 CBatchScanner scanner;
188 scanner.needle = key.str();
189 scanner.deleted = deleted;
190 scanner.foundValue = value;
191 leveldb::Status status = activeBatch->Iterate(&scanner);
193 throw runtime_error(status.ToString());
195 return scanner.foundEntry;
198 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
202 return Read(make_pair(string("tx"), hash), txindex);
205 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
208 return Write(make_pair(string("tx"), hash), txindex);
211 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
216 uint256 hash = tx.GetHash();
217 CTxIndex txindex(pos, tx.vout.size());
218 return Write(make_pair(string("tx"), hash), txindex);
221 bool CTxDB::EraseTxIndex(const CTransaction& tx)
224 uint256 hash = tx.GetHash();
226 return Erase(make_pair(string("tx"), hash));
229 bool CTxDB::ContainsTx(uint256 hash)
232 return Exists(make_pair(string("tx"), hash));
235 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
239 if (!ReadTxIndex(hash, txindex))
241 return (tx.ReadFromDisk(txindex.pos));
244 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
247 return ReadDiskTx(hash, tx, txindex);
250 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
252 return ReadDiskTx(outpoint.hash, tx, txindex);
255 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
258 return ReadDiskTx(outpoint.hash, tx, txindex);
261 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
263 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
266 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
268 return Read(string("hashBestChain"), hashBestChain);
271 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
273 return Write(string("hashBestChain"), hashBestChain);
276 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
278 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
281 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
283 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
286 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
288 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
291 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
293 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
296 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
298 return Read(string("strCheckpointPubKey"), strPubKey);
301 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
303 return Write(string("strCheckpointPubKey"), strPubKey);
306 bool CTxDB::ReadModifierUpgradeTime(unsigned int& nUpgradeTime)
308 return Read(string("nUpgradeTime"), nUpgradeTime);
311 bool CTxDB::WriteModifierUpgradeTime(const unsigned int& nUpgradeTime)
313 return Write(string("nUpgradeTime"), nUpgradeTime);
316 static CBlockIndex *InsertBlockIndex(uint256 hash)
322 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
323 if (mi != mapBlockIndex.end())
327 CBlockIndex* pindexNew = new(nothrow) CBlockIndex();
329 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
330 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
331 pindexNew->phashBlock = &((*mi).first);
336 bool CTxDB::LoadBlockIndex()
338 if (mapBlockIndex.size() > 0) {
339 // Already loaded once in this session. It can happen during migration
343 // The block index is an in-memory structure that maps hashes to on-disk
344 // locations where the contents of the block can be found. Here, we scan it
345 // out of the DB and into mapBlockIndex.
346 leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
347 // Seek to start key.
348 CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
349 ssStartKey << make_pair(string("blockindex"), uint256(0));
350 iterator->Seek(ssStartKey.str());
351 // Now read each entry.
352 while (iterator->Valid())
354 // Unpack keys and values.
355 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
356 ssKey.write(iterator->key().data(), iterator->key().size());
357 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
358 ssValue.write(iterator->value().data(), iterator->value().size());
361 // Did we reach the end of the data to read?
362 if (fRequestShutdown || strType != "blockindex")
364 CDiskBlockIndex diskindex;
365 ssValue >> diskindex;
367 uint256 blockHash = diskindex.GetBlockHash();
369 // Construct block index object
370 CBlockIndex* pindexNew = InsertBlockIndex(blockHash);
371 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
372 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
373 pindexNew->nFile = diskindex.nFile;
374 pindexNew->nBlockPos = diskindex.nBlockPos;
375 pindexNew->nHeight = diskindex.nHeight;
376 pindexNew->nMint = diskindex.nMint;
377 pindexNew->nMoneySupply = diskindex.nMoneySupply;
378 pindexNew->nFlags = diskindex.nFlags;
379 pindexNew->nStakeModifier = diskindex.nStakeModifier;
380 pindexNew->prevoutStake = diskindex.prevoutStake;
381 pindexNew->nStakeTime = diskindex.nStakeTime;
382 pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
383 pindexNew->nVersion = diskindex.nVersion;
384 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
385 pindexNew->nTime = diskindex.nTime;
386 pindexNew->nBits = diskindex.nBits;
387 pindexNew->nNonce = diskindex.nNonce;
389 // Watch for genesis block
390 if (pindexGenesisBlock == NULL && blockHash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
391 pindexGenesisBlock = pindexNew;
393 if (!pindexNew->CheckIndex()) {
395 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
398 // NovaCoin: build setStakeSeen
399 if (pindexNew->IsProofOfStake())
400 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
406 if (fRequestShutdown)
409 // Calculate nChainTrust
410 vector<pair<int, CBlockIndex*> > vSortedByHeight;
411 vSortedByHeight.reserve(mapBlockIndex.size());
412 for (const auto& item : mapBlockIndex)
414 CBlockIndex* pindex = item.second;
415 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
417 sort(vSortedByHeight.begin(), vSortedByHeight.end());
418 for (const auto& item : vSortedByHeight)
420 CBlockIndex* pindex = item.second;
421 pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
422 // NovaCoin: calculate stake modifier checksum
423 pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
424 if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
425 return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindex->nHeight, pindex->nStakeModifier);
428 // Load hashBestChain pointer to end of best chain
429 if (!ReadHashBestChain(hashBestChain))
431 if (pindexGenesisBlock == NULL)
433 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
435 if (!mapBlockIndex.count(hashBestChain))
436 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
437 pindexBest = mapBlockIndex[hashBestChain];
438 nBestHeight = pindexBest->nHeight;
439 nBestChainTrust = pindexBest->nChainTrust;
441 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
442 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
443 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
445 // NovaCoin: load hashSyncCheckpoint
446 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
447 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
448 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
450 // Load bnBestInvalidTrust, OK if it doesn't exist
451 CBigNum bnBestInvalidTrust;
452 ReadBestInvalidTrust(bnBestInvalidTrust);
453 nBestInvalidTrust = bnBestInvalidTrust.getuint256();
455 // Verify blocks in the best chain
456 int nCheckLevel = GetArgInt("-checklevel", 1);
457 int nCheckDepth = GetArgInt( "-checkblocks", 2500);
458 if (nCheckDepth == 0)
459 nCheckDepth = 1000000000; // suffices until the year 19000
460 if (nCheckDepth > nBestHeight)
461 nCheckDepth = nBestHeight;
462 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
463 CBlockIndex* pindexFork = NULL;
464 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
465 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
467 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
470 if (!block.ReadFromDisk(pindex))
471 return error("LoadBlockIndex() : block.ReadFromDisk failed");
472 // check level 1: verify block validity
473 // check level 7: verify block signature too
474 if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
476 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
477 pindexFork = pindex->pprev;
479 // check level 2: verify transaction index validity
482 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
483 mapBlockPos[pos] = pindex;
484 for (const CTransaction &tx : block.vtx)
486 uint256 hashTx = tx.GetHash();
488 if (ReadTxIndex(hashTx, txindex))
490 // check level 3: checker transaction hashes
491 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
493 // either an error or a duplicate transaction
494 CTransaction txFound;
495 if (!txFound.ReadFromDisk(txindex.pos))
497 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
498 pindexFork = pindex->pprev;
501 if (txFound.GetHash() != hashTx) // not a duplicate tx
503 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
504 pindexFork = pindex->pprev;
507 // check level 4: check whether spent txouts were spent within the main chain
508 unsigned int nOutput = 0;
511 for (const CDiskTxPos &txpos : txindex.vSpent)
515 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
516 if (!mapBlockPos.count(posFind))
518 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
519 pindexFork = pindex->pprev;
521 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
524 CTransaction txSpend;
525 if (!txSpend.ReadFromDisk(txpos))
527 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
528 pindexFork = pindex->pprev;
530 else if (!txSpend.CheckTransaction())
532 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
533 pindexFork = pindex->pprev;
538 for (const CTxIn &txin : txSpend.vin)
539 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
543 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
544 pindexFork = pindex->pprev;
553 // check level 5: check whether all prevouts are marked spent
556 for (const CTxIn &txin : tx.vin)
559 if (ReadTxIndex(txin.prevout.hash, txindex))
560 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
562 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
563 pindexFork = pindex->pprev;
570 if (pindexFork && !fRequestShutdown)
572 // Reorg back to the fork
573 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
575 if (!block.ReadFromDisk(pindexFork))
576 return error("LoadBlockIndex() : block.ReadFromDisk failed");
578 block.SetBestChain(txdb, pindexFork);