1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
13 #include <boost/thread.hpp>
17 static const char DB_COINS = 'c';
18 static const char DB_BLOCK_FILES = 'f';
19 static const char DB_TXINDEX = 't';
20 static const char DB_BLOCK_INDEX = 'b';
22 static const char DB_BEST_BLOCK = 'B';
23 static const char DB_FLAG = 'F';
24 static const char DB_REINDEX_FLAG = 'R';
25 static const char DB_LAST_BLOCK = 'l';
28 void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
30 batch.Erase(make_pair(DB_COINS, hash));
32 batch.Write(make_pair(DB_COINS, hash), coins);
35 void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
36 batch.Write(DB_BEST_BLOCK, hash);
39 CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
42 bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
43 return db.Read(make_pair(DB_COINS, txid), coins);
46 bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
47 return db.Exists(make_pair(DB_COINS, txid));
50 uint256 CCoinsViewDB::GetBestBlock() const {
51 uint256 hashBestChain;
52 if (!db.Read(DB_BEST_BLOCK, hashBestChain))
57 bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
61 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
62 if (it->second.flags & CCoinsCacheEntry::DIRTY) {
63 BatchWriteCoins(batch, it->first, it->second.coins);
67 CCoinsMap::iterator itOld = it++;
68 mapCoins.erase(itOld);
70 if (!hashBlock.IsNull())
71 BatchWriteHashBestChain(batch, hashBlock);
73 LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
74 return db.WriteBatch(batch);
77 CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
80 bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
81 return Read(make_pair(DB_BLOCK_FILES, nFile), info);
84 bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
86 return Write(DB_REINDEX_FLAG, '1');
88 return Erase(DB_REINDEX_FLAG);
91 bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
92 fReindexing = Exists(DB_REINDEX_FLAG);
96 bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
97 return Read(DB_LAST_BLOCK, nFile);
100 bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
101 /* It seems that there are no "const iterators" for LevelDB. Since we
102 only need read operations on it, use a const-cast to get around
104 boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator());
105 pcursor->SeekToFirst();
107 CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
108 stats.hashBlock = GetBestBlock();
109 ss << stats.hashBlock;
110 CAmount nTotalAmount = 0;
111 while (pcursor->Valid()) {
112 boost::this_thread::interruption_point();
114 leveldb::Slice slKey = pcursor->key();
115 CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
118 if (chType == DB_COINS) {
119 leveldb::Slice slValue = pcursor->value();
120 CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
126 ss << VARINT(coins.nVersion);
127 ss << (coins.fCoinBase ? 'c' : 'n');
128 ss << VARINT(coins.nHeight);
129 stats.nTransactions++;
130 for (unsigned int i=0; i<coins.vout.size(); i++) {
131 const CTxOut &out = coins.vout[i];
133 stats.nTransactionOutputs++;
136 nTotalAmount += out.nValue;
139 stats.nSerializedSize += 32 + slValue.size();
143 } catch (const std::exception& e) {
144 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
147 stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
148 stats.hashSerialized = ss.GetHash();
149 stats.nTotalAmount = nTotalAmount;
153 bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
155 for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
156 batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
158 batch.Write(DB_LAST_BLOCK, nLastFile);
159 for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
160 batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
162 return WriteBatch(batch, true);
165 bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
166 return Read(make_pair(DB_TXINDEX, txid), pos);
169 bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
171 for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
172 batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
173 return WriteBatch(batch);
176 bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
177 return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
180 bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
182 if (!Read(std::make_pair(DB_FLAG, name), ch))
188 bool CBlockTreeDB::LoadBlockIndexGuts()
190 boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
192 CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
193 ssKeySet << make_pair(DB_BLOCK_INDEX, uint256());
194 pcursor->Seek(ssKeySet.str());
196 // Load mapBlockIndex
197 while (pcursor->Valid()) {
198 boost::this_thread::interruption_point();
200 leveldb::Slice slKey = pcursor->key();
201 CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
204 if (chType == DB_BLOCK_INDEX) {
205 leveldb::Slice slValue = pcursor->value();
206 CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
207 CDiskBlockIndex diskindex;
208 ssValue >> diskindex;
210 // Construct block index object
211 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
212 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
213 pindexNew->nHeight = diskindex.nHeight;
214 pindexNew->nFile = diskindex.nFile;
215 pindexNew->nDataPos = diskindex.nDataPos;
216 pindexNew->nUndoPos = diskindex.nUndoPos;
217 pindexNew->nVersion = diskindex.nVersion;
218 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
219 pindexNew->nTime = diskindex.nTime;
220 pindexNew->nBits = diskindex.nBits;
221 pindexNew->nNonce = diskindex.nNonce;
222 pindexNew->nStatus = diskindex.nStatus;
223 pindexNew->nTx = diskindex.nTx;
225 if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits))
226 return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
230 break; // if shutdown requested or finished loading block index
232 } catch (const std::exception& e) {
233 return error("%s: Deserialize or I/O error - %s", __func__, e.what());