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 void init_blockindex(leveldb::Options& options, bool fRemoveOld = false) {
38 filesystem::path directory = GetDataDir() / "txleveldb";
41 filesystem::remove_all(directory); // remove directory
42 unsigned int nFile = 1;
46 filesystem::path strBlockFile = GetDataDir() / strprintf("blk%04u.dat", nFile);
48 // Break if no such file
49 if( !filesystem::exists( strBlockFile ) )
52 filesystem::remove(strBlockFile);
58 filesystem::create_directory(directory);
59 printf("Opening LevelDB in %s\n", directory.string().c_str());
60 leveldb::Status status = leveldb::DB::Open(options, directory.string(), &txdb);
62 throw runtime_error(strprintf("init_blockindex(): error opening database environment %s", status.ToString().c_str()));
66 // CDB subclasses are created and destroyed VERY OFTEN. That's why
67 // we shouldn't treat this as a free operations.
68 CTxDB::CTxDB(const char* pszMode)
72 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
79 bool fCreate = strchr(pszMode, 'c');
81 options = GetOptions();
82 options.create_if_missing = fCreate;
83 options.filter_policy = leveldb::NewBloomFilterPolicy(10);
85 init_blockindex(options); // Init directory
88 if (Exists(string("version")))
90 ReadVersion(nVersion);
91 printf("Transaction index version is %d\n", nVersion);
93 if (nVersion < DATABASE_VERSION)
95 printf("Required index version is %d, removing old database\n", DATABASE_VERSION);
97 // Leveldb instance destruction
103 init_blockindex(options, true); // Remove directory and create new database
106 bool fTmp = fReadOnly;
108 WriteVersion(DATABASE_VERSION); // Save transaction index version
114 bool fTmp = fReadOnly;
116 WriteVersion(DATABASE_VERSION);
120 printf("Opened LevelDB successfully\n");
127 delete options.filter_policy;
128 options.filter_policy = NULL;
129 delete options.block_cache;
130 options.block_cache = NULL;
135 bool CTxDB::TxnBegin()
137 assert(!activeBatch);
138 activeBatch = new leveldb::WriteBatch();
142 bool CTxDB::TxnCommit()
145 leveldb::Status status = pdb->Write(leveldb::WriteOptions(), activeBatch);
149 printf("LevelDB batch commit failure: %s\n", status.ToString().c_str());
155 class CBatchScanner : public leveldb::WriteBatch::Handler {
159 std::string *foundValue;
162 CBatchScanner() : foundEntry(false) {}
164 virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value) {
165 if (key.ToString() == needle) {
168 *foundValue = value.ToString();
172 virtual void Delete(const leveldb::Slice& key) {
173 if (key.ToString() == needle) {
180 // When performing a read, if we have an active batch we need to check it first
181 // before reading from the database, as the rest of the code assumes that once
182 // a database transaction begins reads are consistent with it. It would be good
183 // to change that assumption in future and avoid the performance hit, though in
184 // practice it does not appear to be large.
185 bool CTxDB::ScanBatch(const CDataStream &key, string *value, bool *deleted) const {
188 CBatchScanner scanner;
189 scanner.needle = key.str();
190 scanner.deleted = deleted;
191 scanner.foundValue = value;
192 leveldb::Status status = activeBatch->Iterate(&scanner);
194 throw runtime_error(status.ToString());
196 return scanner.foundEntry;
199 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
203 return Read(make_pair(string("tx"), hash), txindex);
206 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
209 return Write(make_pair(string("tx"), hash), txindex);
212 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
217 uint256 hash = tx.GetHash();
218 CTxIndex txindex(pos, tx.vout.size());
219 return Write(make_pair(string("tx"), hash), txindex);
222 bool CTxDB::EraseTxIndex(const CTransaction& tx)
225 uint256 hash = tx.GetHash();
227 return Erase(make_pair(string("tx"), hash));
230 bool CTxDB::ContainsTx(uint256 hash)
233 return Exists(make_pair(string("tx"), hash));
236 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
240 if (!ReadTxIndex(hash, txindex))
242 return (tx.ReadFromDisk(txindex.pos));
245 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
248 return ReadDiskTx(hash, tx, txindex);
251 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
253 return ReadDiskTx(outpoint.hash, tx, txindex);
256 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
259 return ReadDiskTx(outpoint.hash, tx, txindex);
262 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
264 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
267 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
269 return Read(string("hashBestChain"), hashBestChain);
272 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
274 return Write(string("hashBestChain"), hashBestChain);
277 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
279 return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
282 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
284 return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
287 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
289 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
292 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
294 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
297 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
299 return Read(string("strCheckpointPubKey"), strPubKey);
302 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
304 return Write(string("strCheckpointPubKey"), strPubKey);
307 bool CTxDB::ReadModifierUpgradeTime(unsigned int& nUpgradeTime)
309 return Read(string("nUpgradeTime"), nUpgradeTime);
312 bool CTxDB::WriteModifierUpgradeTime(const unsigned int& nUpgradeTime)
314 return Write(string("nUpgradeTime"), nUpgradeTime);
317 static CBlockIndex *InsertBlockIndex(uint256 hash)
323 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
324 if (mi != mapBlockIndex.end())
328 CBlockIndex* pindexNew = new CBlockIndex();
330 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
331 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
332 pindexNew->phashBlock = &((*mi).first);
337 bool CTxDB::LoadBlockIndex()
339 if (mapBlockIndex.size() > 0) {
340 // Already loaded once in this session. It can happen during migration
344 // The block index is an in-memory structure that maps hashes to on-disk
345 // locations where the contents of the block can be found. Here, we scan it
346 // out of the DB and into mapBlockIndex.
347 leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
348 // Seek to start key.
349 CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
350 ssStartKey << make_pair(string("blockindex"), uint256(0));
351 iterator->Seek(ssStartKey.str());
352 // Now read each entry.
353 while (iterator->Valid())
355 // Unpack keys and values.
356 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
357 ssKey.write(iterator->key().data(), iterator->key().size());
358 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
359 ssValue.write(iterator->value().data(), iterator->value().size());
362 // Did we reach the end of the data to read?
363 if (fRequestShutdown || strType != "blockindex")
365 CDiskBlockIndex diskindex;
366 ssValue >> diskindex;
368 uint256 blockHash = diskindex.GetBlockHash();
370 // Construct block index object
371 CBlockIndex* pindexNew = InsertBlockIndex(blockHash);
372 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
373 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
374 pindexNew->nFile = diskindex.nFile;
375 pindexNew->nBlockPos = diskindex.nBlockPos;
376 pindexNew->nHeight = diskindex.nHeight;
377 pindexNew->nMint = diskindex.nMint;
378 pindexNew->nMoneySupply = diskindex.nMoneySupply;
379 pindexNew->nFlags = diskindex.nFlags;
380 pindexNew->nStakeModifier = diskindex.nStakeModifier;
381 pindexNew->prevoutStake = diskindex.prevoutStake;
382 pindexNew->nStakeTime = diskindex.nStakeTime;
383 pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
384 pindexNew->nVersion = diskindex.nVersion;
385 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
386 pindexNew->nTime = diskindex.nTime;
387 pindexNew->nBits = diskindex.nBits;
388 pindexNew->nNonce = diskindex.nNonce;
390 // Watch for genesis block
391 if (pindexGenesisBlock == NULL && blockHash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
392 pindexGenesisBlock = pindexNew;
394 if (!pindexNew->CheckIndex()) {
396 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
399 // NovaCoin: build setStakeSeen
400 if (pindexNew->IsProofOfStake())
401 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
407 if (fRequestShutdown)
410 // Calculate nChainTrust
411 vector<pair<int, CBlockIndex*> > vSortedByHeight;
412 vSortedByHeight.reserve(mapBlockIndex.size());
413 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
415 CBlockIndex* pindex = item.second;
416 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
418 sort(vSortedByHeight.begin(), vSortedByHeight.end());
419 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
421 CBlockIndex* pindex = item.second;
422 pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
423 // NovaCoin: calculate stake modifier checksum
424 pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
425 if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
426 return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindex->nHeight, pindex->nStakeModifier);
429 // Load hashBestChain pointer to end of best chain
430 if (!ReadHashBestChain(hashBestChain))
432 if (pindexGenesisBlock == NULL)
434 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
436 if (!mapBlockIndex.count(hashBestChain))
437 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
438 pindexBest = mapBlockIndex[hashBestChain];
439 nBestHeight = pindexBest->nHeight;
440 nBestChainTrust = pindexBest->nChainTrust;
442 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
443 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
444 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
446 // NovaCoin: load hashSyncCheckpoint
447 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
448 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
449 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
451 // Load bnBestInvalidTrust, OK if it doesn't exist
452 CBigNum bnBestInvalidTrust;
453 ReadBestInvalidTrust(bnBestInvalidTrust);
454 nBestInvalidTrust = bnBestInvalidTrust.getuint256();
456 // Verify blocks in the best chain
457 int nCheckLevel = GetArg("-checklevel", 1);
458 int nCheckDepth = GetArg( "-checkblocks", 2500);
459 if (nCheckDepth == 0)
460 nCheckDepth = 1000000000; // suffices until the year 19000
461 if (nCheckDepth > nBestHeight)
462 nCheckDepth = nBestHeight;
463 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
464 CBlockIndex* pindexFork = NULL;
465 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
466 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
468 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
471 if (!block.ReadFromDisk(pindex))
472 return error("LoadBlockIndex() : block.ReadFromDisk failed");
473 // check level 1: verify block validity
474 // check level 7: verify block signature too
475 if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
477 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
478 pindexFork = pindex->pprev;
480 // check level 2: verify transaction index validity
483 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
484 mapBlockPos[pos] = pindex;
485 BOOST_FOREACH(const CTransaction &tx, block.vtx)
487 uint256 hashTx = tx.GetHash();
489 if (ReadTxIndex(hashTx, txindex))
491 // check level 3: checker transaction hashes
492 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
494 // either an error or a duplicate transaction
495 CTransaction txFound;
496 if (!txFound.ReadFromDisk(txindex.pos))
498 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
499 pindexFork = pindex->pprev;
502 if (txFound.GetHash() != hashTx) // not a duplicate tx
504 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
505 pindexFork = pindex->pprev;
508 // check level 4: check whether spent txouts were spent within the main chain
509 unsigned int nOutput = 0;
512 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
516 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
517 if (!mapBlockPos.count(posFind))
519 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
520 pindexFork = pindex->pprev;
522 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
525 CTransaction txSpend;
526 if (!txSpend.ReadFromDisk(txpos))
528 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
529 pindexFork = pindex->pprev;
531 else if (!txSpend.CheckTransaction())
533 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
534 pindexFork = pindex->pprev;
539 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
540 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
544 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
545 pindexFork = pindex->pprev;
554 // check level 5: check whether all prevouts are marked spent
557 BOOST_FOREACH(const CTxIn &txin, tx.vin)
560 if (ReadTxIndex(txin.prevout.hash, txindex))
561 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
563 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
564 pindexFork = pindex->pprev;
571 if (pindexFork && !fRequestShutdown)
573 // Reorg back to the fork
574 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
576 if (!block.ReadFromDisk(pindexFork))
577 return error("LoadBlockIndex() : block.ReadFromDisk failed");
579 block.SetBestChain(txdb, pindexFork);