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.
8 #include "chainparams.h"
16 #include <boost/thread.hpp>
20 static const char DB_ANCHOR = 'A';
21 static const char DB_NULLIFIER = 's';
22 static const char DB_COINS = 'c';
23 static const char DB_BLOCK_FILES = 'f';
24 static const char DB_TXINDEX = 't';
25 static const char DB_BLOCK_INDEX = 'b';
27 static const char DB_BEST_BLOCK = 'B';
28 static const char DB_BEST_ANCHOR = 'a';
29 static const char DB_FLAG = 'F';
30 static const char DB_REINDEX_FLAG = 'R';
31 static const char DB_LAST_BLOCK = 'l';
34 void static BatchWriteAnchor(CLevelDBBatch &batch,
36 const ZCIncrementalMerkleTree &tree,
40 batch.Erase(make_pair(DB_ANCHOR, croot));
42 batch.Write(make_pair(DB_ANCHOR, croot), tree);
46 void static BatchWriteNullifier(CLevelDBBatch &batch, const uint256 &nf, const bool &entered) {
48 batch.Erase(make_pair(DB_NULLIFIER, nf));
50 batch.Write(make_pair(DB_NULLIFIER, nf), true);
53 void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
55 batch.Erase(make_pair(DB_COINS, hash));
57 batch.Write(make_pair(DB_COINS, hash), coins);
60 void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
61 batch.Write(DB_BEST_BLOCK, hash);
64 void static BatchWriteHashBestAnchor(CLevelDBBatch &batch, const uint256 &hash) {
65 batch.Write(DB_BEST_ANCHOR, hash);
68 CCoinsViewDB::CCoinsViewDB(std::string dbName, size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / dbName, nCacheSize, fMemory, fWipe) {
71 CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
75 bool CCoinsViewDB::GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const {
76 if (rt == ZCIncrementalMerkleTree::empty_root()) {
77 ZCIncrementalMerkleTree new_tree;
82 bool read = db.Read(make_pair(DB_ANCHOR, rt), tree);
87 bool CCoinsViewDB::GetNullifier(const uint256 &nf) const {
89 bool read = db.Read(make_pair(DB_NULLIFIER, nf), spent);
94 bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
95 return db.Read(make_pair(DB_COINS, txid), coins);
98 bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
99 return db.Exists(make_pair(DB_COINS, txid));
102 uint256 CCoinsViewDB::GetBestBlock() const {
103 uint256 hashBestChain;
104 if (!db.Read(DB_BEST_BLOCK, hashBestChain))
106 return hashBestChain;
109 uint256 CCoinsViewDB::GetBestAnchor() const {
110 uint256 hashBestAnchor;
111 if (!db.Read(DB_BEST_ANCHOR, hashBestAnchor))
112 return ZCIncrementalMerkleTree::empty_root();
113 return hashBestAnchor;
116 bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins,
117 const uint256 &hashBlock,
118 const uint256 &hashAnchor,
119 CAnchorsMap &mapAnchors,
120 CNullifiersMap &mapNullifiers) {
124 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
125 if (it->second.flags & CCoinsCacheEntry::DIRTY) {
126 BatchWriteCoins(batch, it->first, it->second.coins);
130 CCoinsMap::iterator itOld = it++;
131 mapCoins.erase(itOld);
134 for (CAnchorsMap::iterator it = mapAnchors.begin(); it != mapAnchors.end();) {
135 if (it->second.flags & CAnchorsCacheEntry::DIRTY) {
136 BatchWriteAnchor(batch, it->first, it->second.tree, it->second.entered);
139 CAnchorsMap::iterator itOld = it++;
140 mapAnchors.erase(itOld);
143 for (CNullifiersMap::iterator it = mapNullifiers.begin(); it != mapNullifiers.end();) {
144 if (it->second.flags & CNullifiersCacheEntry::DIRTY) {
145 BatchWriteNullifier(batch, it->first, it->second.entered);
148 CNullifiersMap::iterator itOld = it++;
149 mapNullifiers.erase(itOld);
152 if (!hashBlock.IsNull())
153 BatchWriteHashBestChain(batch, hashBlock);
154 if (!hashAnchor.IsNull())
155 BatchWriteHashBestAnchor(batch, hashAnchor);
157 LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
158 return db.WriteBatch(batch);
161 CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
164 bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
165 return Read(make_pair(DB_BLOCK_FILES, nFile), info);
168 bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
170 return Write(DB_REINDEX_FLAG, '1');
172 return Erase(DB_REINDEX_FLAG);
175 bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
176 fReindexing = Exists(DB_REINDEX_FLAG);
180 bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
181 return Read(DB_LAST_BLOCK, nFile);
184 bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
185 /* It seems that there are no "const iterators" for LevelDB. Since we
186 only need read operations on it, use a const-cast to get around
188 boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator());
189 pcursor->SeekToFirst();
191 CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
192 stats.hashBlock = GetBestBlock();
193 ss << stats.hashBlock;
194 CAmount nTotalAmount = 0;
195 while (pcursor->Valid()) {
196 boost::this_thread::interruption_point();
198 leveldb::Slice slKey = pcursor->key();
199 CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
202 if (chType == DB_COINS) {
203 leveldb::Slice slValue = pcursor->value();
204 CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
210 ss << VARINT(coins.nVersion);
211 ss << (coins.fCoinBase ? 'c' : 'n');
212 ss << VARINT(coins.nHeight);
213 stats.nTransactions++;
214 for (unsigned int i=0; i<coins.vout.size(); i++) {
215 const CTxOut &out = coins.vout[i];
217 stats.nTransactionOutputs++;
220 nTotalAmount += out.nValue;
223 stats.nSerializedSize += 32 + slValue.size();
227 } catch (const std::exception& e) {
228 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
233 stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
235 stats.hashSerialized = ss.GetHash();
236 stats.nTotalAmount = nTotalAmount;
240 bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
242 for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
243 batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
245 batch.Write(DB_LAST_BLOCK, nLastFile);
246 for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
247 batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
249 return WriteBatch(batch, true);
252 bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
253 return Read(make_pair(DB_TXINDEX, txid), pos);
256 bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
258 for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
259 batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
260 return WriteBatch(batch);
263 bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
264 return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
267 bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
269 if (!Read(std::make_pair(DB_FLAG, name), ch))
275 bool CBlockTreeDB::LoadBlockIndexGuts()
277 boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
279 CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
280 ssKeySet << make_pair(DB_BLOCK_INDEX, uint256());
281 pcursor->Seek(ssKeySet.str());
283 // Load mapBlockIndex
284 while (pcursor->Valid()) {
285 boost::this_thread::interruption_point();
287 leveldb::Slice slKey = pcursor->key();
288 CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
291 if (chType == DB_BLOCK_INDEX) {
292 leveldb::Slice slValue = pcursor->value();
293 CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
294 CDiskBlockIndex diskindex;
295 ssValue >> diskindex;
297 // Construct block index object
298 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
299 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
300 pindexNew->nHeight = diskindex.nHeight;
301 pindexNew->nFile = diskindex.nFile;
302 pindexNew->nDataPos = diskindex.nDataPos;
303 pindexNew->nUndoPos = diskindex.nUndoPos;
304 pindexNew->hashAnchor = diskindex.hashAnchor;
305 pindexNew->nVersion = diskindex.nVersion;
306 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
307 pindexNew->nTime = diskindex.nTime;
308 pindexNew->nBits = diskindex.nBits;
309 pindexNew->nNonce = diskindex.nNonce;
310 pindexNew->nSolution = diskindex.nSolution;
311 pindexNew->nStatus = diskindex.nStatus;
312 pindexNew->nTx = diskindex.nTx;
314 if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
315 return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
319 break; // if shutdown requested or finished loading block index
321 } catch (const std::exception& e) {
322 return error("%s: Deserialize or I/O error - %s", __func__, e.what());