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 // NOTE: Per issue #3277, do not use the prefix 'X' or 'x' as they were
21 // previously used by DB_SAPLING_ANCHOR and DB_BEST_SAPLING_ANCHOR.
22 static const char DB_SPROUT_ANCHOR = 'A';
23 static const char DB_SAPLING_ANCHOR = 'Z';
24 static const char DB_NULLIFIER = 's';
25 static const char DB_SAPLING_NULLIFIER = 'S';
26 static const char DB_COINS = 'c';
27 static const char DB_BLOCK_FILES = 'f';
28 static const char DB_TXINDEX = 't';
29 static const char DB_BLOCK_INDEX = 'b';
31 static const char DB_BEST_BLOCK = 'B';
32 static const char DB_BEST_SPROUT_ANCHOR = 'a';
33 static const char DB_BEST_SAPLING_ANCHOR = 'z';
34 static const char DB_FLAG = 'F';
35 static const char DB_REINDEX_FLAG = 'R';
36 static const char DB_LAST_BLOCK = 'l';
39 CCoinsViewDB::CCoinsViewDB(std::string dbName, size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / dbName, nCacheSize, fMemory, fWipe) {
42 CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe)
47 bool CCoinsViewDB::GetSproutAnchorAt(const uint256 &rt, SproutMerkleTree &tree) const {
48 if (rt == SproutMerkleTree::empty_root()) {
49 SproutMerkleTree new_tree;
54 bool read = db.Read(make_pair(DB_SPROUT_ANCHOR, rt), tree);
59 bool CCoinsViewDB::GetSaplingAnchorAt(const uint256 &rt, SaplingMerkleTree &tree) const {
60 if (rt == SaplingMerkleTree::empty_root()) {
61 SaplingMerkleTree new_tree;
66 bool read = db.Read(make_pair(DB_SAPLING_ANCHOR, rt), tree);
71 bool CCoinsViewDB::GetNullifier(const uint256 &nf, ShieldedType type) const {
76 dbChar = DB_NULLIFIER;
79 dbChar = DB_SAPLING_NULLIFIER;
82 throw runtime_error("Unknown shielded type");
84 return db.Read(make_pair(dbChar, nf), spent);
87 bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
88 return db.Read(make_pair(DB_COINS, txid), coins);
91 bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
92 return db.Exists(make_pair(DB_COINS, txid));
95 uint256 CCoinsViewDB::GetBestBlock() const {
96 uint256 hashBestChain;
97 if (!db.Read(DB_BEST_BLOCK, hashBestChain))
102 uint256 CCoinsViewDB::GetBestAnchor(ShieldedType type) const {
103 uint256 hashBestAnchor;
107 if (!db.Read(DB_BEST_SPROUT_ANCHOR, hashBestAnchor))
108 return SproutMerkleTree::empty_root();
111 if (!db.Read(DB_BEST_SAPLING_ANCHOR, hashBestAnchor))
112 return SaplingMerkleTree::empty_root();
115 throw runtime_error("Unknown shielded type");
118 return hashBestAnchor;
121 void BatchWriteNullifiers(CDBBatch& batch, CNullifiersMap& mapToUse, const char& dbChar)
123 for (CNullifiersMap::iterator it = mapToUse.begin(); it != mapToUse.end();) {
124 if (it->second.flags & CNullifiersCacheEntry::DIRTY) {
125 if (!it->second.entered)
126 batch.Erase(make_pair(dbChar, it->first));
128 batch.Write(make_pair(dbChar, it->first), true);
129 // TODO: changed++? ... See comment in CCoinsViewDB::BatchWrite. If this is needed we could return an int
131 CNullifiersMap::iterator itOld = it++;
132 mapToUse.erase(itOld);
136 template<typename Map, typename MapIterator, typename MapEntry, typename Tree>
137 void BatchWriteAnchors(CDBBatch& batch, Map& mapToUse, const char& dbChar)
139 for (MapIterator it = mapToUse.begin(); it != mapToUse.end();) {
140 if (it->second.flags & MapEntry::DIRTY) {
141 if (!it->second.entered)
142 batch.Erase(make_pair(dbChar, it->first));
144 if (it->first != Tree::empty_root()) {
145 batch.Write(make_pair(dbChar, it->first), it->second.tree);
150 MapIterator itOld = it++;
151 mapToUse.erase(itOld);
155 bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins,
156 const uint256 &hashBlock,
157 const uint256 &hashSproutAnchor,
158 const uint256 &hashSaplingAnchor,
159 CAnchorsSproutMap &mapSproutAnchors,
160 CAnchorsSaplingMap &mapSaplingAnchors,
161 CNullifiersMap &mapSproutNullifiers,
162 CNullifiersMap &mapSaplingNullifiers) {
166 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
167 if (it->second.flags & CCoinsCacheEntry::DIRTY) {
168 if (it->second.coins.IsPruned())
169 batch.Erase(make_pair(DB_COINS, it->first));
171 batch.Write(make_pair(DB_COINS, it->first), it->second.coins);
175 CCoinsMap::iterator itOld = it++;
176 mapCoins.erase(itOld);
179 ::BatchWriteAnchors<CAnchorsSproutMap, CAnchorsSproutMap::iterator, CAnchorsSproutCacheEntry, SproutMerkleTree>(batch, mapSproutAnchors, DB_SPROUT_ANCHOR);
180 ::BatchWriteAnchors<CAnchorsSaplingMap, CAnchorsSaplingMap::iterator, CAnchorsSaplingCacheEntry, SaplingMerkleTree>(batch, mapSaplingAnchors, DB_SAPLING_ANCHOR);
182 ::BatchWriteNullifiers(batch, mapSproutNullifiers, DB_NULLIFIER);
183 ::BatchWriteNullifiers(batch, mapSaplingNullifiers, DB_SAPLING_NULLIFIER);
185 if (!hashBlock.IsNull())
186 batch.Write(DB_BEST_BLOCK, hashBlock);
187 if (!hashSproutAnchor.IsNull() && hashSproutAnchor != SproutMerkleTree::empty_root())
188 batch.Write(DB_BEST_SPROUT_ANCHOR, hashSproutAnchor);
189 if (!hashSaplingAnchor.IsNull() && hashSaplingAnchor != SaplingMerkleTree::empty_root())
190 batch.Write(DB_BEST_SAPLING_ANCHOR, hashSaplingAnchor);
192 LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
193 return db.WriteBatch(batch);
196 CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
199 bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
200 return Read(make_pair(DB_BLOCK_FILES, nFile), info);
203 bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
205 return Write(DB_REINDEX_FLAG, '1');
207 return Erase(DB_REINDEX_FLAG);
210 bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
211 fReindexing = Exists(DB_REINDEX_FLAG);
215 bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
216 return Read(DB_LAST_BLOCK, nFile);
219 bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
220 /* It seems that there are no "const iterators" for LevelDB. Since we
221 only need read operations on it, use a const-cast to get around
223 boost::scoped_ptr<CDBIterator> pcursor(const_cast<CDBWrapper*>(&db)->NewIterator());
224 pcursor->Seek(DB_COINS);
226 CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
227 stats.hashBlock = GetBestBlock();
228 ss << stats.hashBlock;
229 CAmount nTotalAmount = 0;
230 while (pcursor->Valid()) {
231 boost::this_thread::interruption_point();
232 std::pair<char, uint256> key;
234 if (pcursor->GetKey(key) && key.first == DB_COINS) {
235 if (pcursor->GetValue(coins)) {
236 stats.nTransactions++;
237 for (unsigned int i=0; i<coins.vout.size(); i++) {
238 const CTxOut &out = coins.vout[i];
240 stats.nTransactionOutputs++;
243 nTotalAmount += out.nValue;
246 stats.nSerializedSize += 32 + pcursor->GetValueSize();
249 return error("CCoinsViewDB::GetStats() : unable to read value");
258 stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
260 stats.hashSerialized = ss.GetHash();
261 stats.nTotalAmount = nTotalAmount;
265 bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
266 CDBBatch batch(*this);
267 for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
268 batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
270 batch.Write(DB_LAST_BLOCK, nLastFile);
271 for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
272 batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
274 return WriteBatch(batch, true);
277 bool CBlockTreeDB::EraseBatchSync(const std::vector<const CBlockIndex*>& blockinfo) {
278 CDBBatch batch(*this);
279 for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
280 batch.Erase(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()));
282 return WriteBatch(batch, true);
285 bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
286 return Read(make_pair(DB_TXINDEX, txid), pos);
289 bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
290 CDBBatch batch(*this);
291 for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
292 batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
293 return WriteBatch(batch);
296 bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
297 return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
300 bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
302 if (!Read(std::make_pair(DB_FLAG, name), ch))
308 bool CBlockTreeDB::LoadBlockIndexGuts()
310 boost::scoped_ptr<CDBIterator> pcursor(NewIterator());
312 pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));
314 // Load mapBlockIndex
315 while (pcursor->Valid()) {
316 boost::this_thread::interruption_point();
317 std::pair<char, uint256> key;
318 if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
319 CDiskBlockIndex diskindex;
320 if (pcursor->GetValue(diskindex)) {
321 // Construct block index object
322 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
323 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
324 pindexNew->nHeight = diskindex.nHeight;
325 pindexNew->nFile = diskindex.nFile;
326 pindexNew->nDataPos = diskindex.nDataPos;
327 pindexNew->nUndoPos = diskindex.nUndoPos;
328 pindexNew->hashSproutAnchor = diskindex.hashSproutAnchor;
329 pindexNew->nVersion = diskindex.nVersion;
330 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
331 pindexNew->hashFinalSaplingRoot = diskindex.hashFinalSaplingRoot;
332 pindexNew->nTime = diskindex.nTime;
333 pindexNew->nBits = diskindex.nBits;
334 pindexNew->nNonce = diskindex.nNonce;
335 pindexNew->nSolution = diskindex.nSolution;
336 pindexNew->nStatus = diskindex.nStatus;
337 pindexNew->nCachedBranchId = diskindex.nCachedBranchId;
338 pindexNew->nTx = diskindex.nTx;
339 pindexNew->nSproutValue = diskindex.nSproutValue;
341 // Consistency checks
342 auto header = pindexNew->GetBlockHeader();
343 if (header.GetHash() != pindexNew->GetBlockHash())
344 return error("LoadBlockIndex(): block header inconsistency detected: on-disk = %s, in-memory = %s",
345 diskindex.ToString(), pindexNew->ToString());
346 if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
347 return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
351 return error("LoadBlockIndex() : failed to read value");