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(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
72 bool CCoinsViewDB::GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const {
73 if (rt == ZCIncrementalMerkleTree::empty_root()) {
74 ZCIncrementalMerkleTree new_tree;
79 bool read = db.Read(make_pair(DB_ANCHOR, rt), tree);
84 bool CCoinsViewDB::GetNullifier(const uint256 &nf) const {
86 bool read = db.Read(make_pair(DB_NULLIFIER, nf), spent);
91 bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
92 return db.Read(make_pair(DB_COINS, txid), coins);
95 bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
96 return db.Exists(make_pair(DB_COINS, txid));
99 uint256 CCoinsViewDB::GetBestBlock() const {
100 uint256 hashBestChain;
101 if (!db.Read(DB_BEST_BLOCK, hashBestChain))
103 return hashBestChain;
106 uint256 CCoinsViewDB::GetBestAnchor() const {
107 uint256 hashBestAnchor;
108 if (!db.Read(DB_BEST_ANCHOR, hashBestAnchor))
109 return ZCIncrementalMerkleTree::empty_root();
110 return hashBestAnchor;
113 bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins,
114 const uint256 &hashBlock,
115 const uint256 &hashAnchor,
116 CAnchorsMap &mapAnchors,
117 CNullifiersMap &mapNullifiers) {
121 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
122 if (it->second.flags & CCoinsCacheEntry::DIRTY) {
123 BatchWriteCoins(batch, it->first, it->second.coins);
127 CCoinsMap::iterator itOld = it++;
128 mapCoins.erase(itOld);
131 for (CAnchorsMap::iterator it = mapAnchors.begin(); it != mapAnchors.end();) {
132 if (it->second.flags & CAnchorsCacheEntry::DIRTY) {
133 BatchWriteAnchor(batch, it->first, it->second.tree, it->second.entered);
136 CAnchorsMap::iterator itOld = it++;
137 mapAnchors.erase(itOld);
140 for (CNullifiersMap::iterator it = mapNullifiers.begin(); it != mapNullifiers.end();) {
141 if (it->second.flags & CNullifiersCacheEntry::DIRTY) {
142 BatchWriteNullifier(batch, it->first, it->second.entered);
145 CNullifiersMap::iterator itOld = it++;
146 mapNullifiers.erase(itOld);
149 if (!hashBlock.IsNull())
150 BatchWriteHashBestChain(batch, hashBlock);
151 if (!hashAnchor.IsNull())
152 BatchWriteHashBestAnchor(batch, hashAnchor);
154 LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
155 return db.WriteBatch(batch);
158 CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
161 bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
162 return Read(make_pair(DB_BLOCK_FILES, nFile), info);
165 bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
167 return Write(DB_REINDEX_FLAG, '1');
169 return Erase(DB_REINDEX_FLAG);
172 bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
173 fReindexing = Exists(DB_REINDEX_FLAG);
177 bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
178 return Read(DB_LAST_BLOCK, nFile);
181 bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
182 /* It seems that there are no "const iterators" for LevelDB. Since we
183 only need read operations on it, use a const-cast to get around
185 boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator());
186 pcursor->SeekToFirst();
188 CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
189 stats.hashBlock = GetBestBlock();
190 ss << stats.hashBlock;
191 CAmount nTotalAmount = 0;
192 while (pcursor->Valid()) {
193 boost::this_thread::interruption_point();
195 leveldb::Slice slKey = pcursor->key();
196 CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
199 if (chType == DB_COINS) {
200 leveldb::Slice slValue = pcursor->value();
201 CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
207 ss << VARINT(coins.nVersion);
208 ss << (coins.fCoinBase ? 'c' : 'n');
209 ss << VARINT(coins.nHeight);
210 stats.nTransactions++;
211 for (unsigned int i=0; i<coins.vout.size(); i++) {
212 const CTxOut &out = coins.vout[i];
214 stats.nTransactionOutputs++;
217 nTotalAmount += out.nValue;
220 stats.nSerializedSize += 32 + slValue.size();
224 } catch (const std::exception& e) {
225 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
228 stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
229 stats.hashSerialized = ss.GetHash();
230 stats.nTotalAmount = nTotalAmount;
234 bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
236 for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
237 batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
239 batch.Write(DB_LAST_BLOCK, nLastFile);
240 for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
241 batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
243 return WriteBatch(batch, true);
246 bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
247 return Read(make_pair(DB_TXINDEX, txid), pos);
250 bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
252 for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
253 batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
254 return WriteBatch(batch);
257 bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
258 return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
261 bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
263 if (!Read(std::make_pair(DB_FLAG, name), ch))
269 bool CBlockTreeDB::LoadBlockIndexGuts()
271 boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
273 CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
274 ssKeySet << make_pair(DB_BLOCK_INDEX, uint256());
275 pcursor->Seek(ssKeySet.str());
277 // Load mapBlockIndex
278 while (pcursor->Valid()) {
279 boost::this_thread::interruption_point();
281 leveldb::Slice slKey = pcursor->key();
282 CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
285 if (chType == DB_BLOCK_INDEX) {
286 leveldb::Slice slValue = pcursor->value();
287 CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
288 CDiskBlockIndex diskindex;
289 ssValue >> diskindex;
291 // Construct block index object
292 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
293 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
294 pindexNew->nHeight = diskindex.nHeight;
295 pindexNew->nFile = diskindex.nFile;
296 pindexNew->nDataPos = diskindex.nDataPos;
297 pindexNew->nUndoPos = diskindex.nUndoPos;
298 pindexNew->hashAnchor = diskindex.hashAnchor;
299 pindexNew->nVersion = diskindex.nVersion;
300 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
301 pindexNew->nTime = diskindex.nTime;
302 pindexNew->nBits = diskindex.nBits;
303 pindexNew->nNonce = diskindex.nNonce;
304 pindexNew->nSolution = diskindex.nSolution;
305 pindexNew->nStatus = diskindex.nStatus;
306 pindexNew->nTx = diskindex.nTx;
308 if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
309 return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
313 break; // if shutdown requested or finished loading block index
315 } catch (const std::exception& e) {
316 return error("%s: Deserialize or I/O error - %s", __func__, e.what());