]> Git Repo - VerusCoin.git/blob - src/txdb.cpp
Auto merge of #2372 - str4d:2355-connectblock-bench, r=nathan-at-least
[VerusCoin.git] / src / txdb.cpp
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.
5
6 #include "txdb.h"
7
8 #include "chainparams.h"
9 #include "hash.h"
10 #include "main.h"
11 #include "pow.h"
12 #include "uint256.h"
13
14 #include <stdint.h>
15
16 #include <boost/thread.hpp>
17
18 using namespace std;
19
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';
26
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';
32
33
34 void static BatchWriteAnchor(CLevelDBBatch &batch,
35                              const uint256 &croot,
36                              const ZCIncrementalMerkleTree &tree,
37                              const bool &entered)
38 {
39     if (!entered)
40         batch.Erase(make_pair(DB_ANCHOR, croot));
41     else {
42         batch.Write(make_pair(DB_ANCHOR, croot), tree);
43     }
44 }
45
46 void static BatchWriteNullifier(CLevelDBBatch &batch, const uint256 &nf, const bool &entered) {
47     if (!entered)
48         batch.Erase(make_pair(DB_NULLIFIER, nf));
49     else
50         batch.Write(make_pair(DB_NULLIFIER, nf), true);
51 }
52
53 void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
54     if (coins.IsPruned())
55         batch.Erase(make_pair(DB_COINS, hash));
56     else
57         batch.Write(make_pair(DB_COINS, hash), coins);
58 }
59
60 void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
61     batch.Write(DB_BEST_BLOCK, hash);
62 }
63
64 void static BatchWriteHashBestAnchor(CLevelDBBatch &batch, const uint256 &hash) {
65     batch.Write(DB_BEST_ANCHOR, hash);
66 }
67
68 CCoinsViewDB::CCoinsViewDB(std::string dbName, size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / dbName, nCacheSize, fMemory, fWipe) {
69 }
70
71 CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
72 }
73
74
75 bool CCoinsViewDB::GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const {
76     if (rt == ZCIncrementalMerkleTree::empty_root()) {
77         ZCIncrementalMerkleTree new_tree;
78         tree = new_tree;
79         return true;
80     }
81
82     bool read = db.Read(make_pair(DB_ANCHOR, rt), tree);
83
84     return read;
85 }
86
87 bool CCoinsViewDB::GetNullifier(const uint256 &nf) const {
88     bool spent = false;
89     bool read = db.Read(make_pair(DB_NULLIFIER, nf), spent);
90
91     return read;
92 }
93
94 bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
95     return db.Read(make_pair(DB_COINS, txid), coins);
96 }
97
98 bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
99     return db.Exists(make_pair(DB_COINS, txid));
100 }
101
102 uint256 CCoinsViewDB::GetBestBlock() const {
103     uint256 hashBestChain;
104     if (!db.Read(DB_BEST_BLOCK, hashBestChain))
105         return uint256();
106     return hashBestChain;
107 }
108
109 uint256 CCoinsViewDB::GetBestAnchor() const {
110     uint256 hashBestAnchor;
111     if (!db.Read(DB_BEST_ANCHOR, hashBestAnchor))
112         return ZCIncrementalMerkleTree::empty_root();
113     return hashBestAnchor;
114 }
115
116 bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins,
117                               const uint256 &hashBlock,
118                               const uint256 &hashAnchor,
119                               CAnchorsMap &mapAnchors,
120                               CNullifiersMap &mapNullifiers) {
121     CLevelDBBatch batch;
122     size_t count = 0;
123     size_t changed = 0;
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);
127             changed++;
128         }
129         count++;
130         CCoinsMap::iterator itOld = it++;
131         mapCoins.erase(itOld);
132     }
133
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);
137             // TODO: changed++?
138         }
139         CAnchorsMap::iterator itOld = it++;
140         mapAnchors.erase(itOld);
141     }
142
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);
146             // TODO: changed++?
147         }
148         CNullifiersMap::iterator itOld = it++;
149         mapNullifiers.erase(itOld);
150     }
151
152     if (!hashBlock.IsNull())
153         BatchWriteHashBestChain(batch, hashBlock);
154     if (!hashAnchor.IsNull())
155         BatchWriteHashBestAnchor(batch, hashAnchor);
156
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);
159 }
160
161 CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
162 }
163
164 bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
165     return Read(make_pair(DB_BLOCK_FILES, nFile), info);
166 }
167
168 bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
169     if (fReindexing)
170         return Write(DB_REINDEX_FLAG, '1');
171     else
172         return Erase(DB_REINDEX_FLAG);
173 }
174
175 bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
176     fReindexing = Exists(DB_REINDEX_FLAG);
177     return true;
178 }
179
180 bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
181     return Read(DB_LAST_BLOCK, nFile);
182 }
183
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
187        that restriction.  */
188     boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator());
189     pcursor->SeekToFirst();
190
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();
197         try {
198             leveldb::Slice slKey = pcursor->key();
199             CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
200             char chType;
201             ssKey >> chType;
202             if (chType == DB_COINS) {
203                 leveldb::Slice slValue = pcursor->value();
204                 CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
205                 CCoins coins;
206                 ssValue >> coins;
207                 uint256 txhash;
208                 ssKey >> txhash;
209                 ss << txhash;
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];
216                     if (!out.IsNull()) {
217                         stats.nTransactionOutputs++;
218                         ss << VARINT(i+1);
219                         ss << out;
220                         nTotalAmount += out.nValue;
221                     }
222                 }
223                 stats.nSerializedSize += 32 + slValue.size();
224                 ss << VARINT(0);
225             }
226             pcursor->Next();
227         } catch (const std::exception& e) {
228             return error("%s: Deserialize or I/O error - %s", __func__, e.what());
229         }
230     }
231     {
232         LOCK(cs_main);
233         stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
234     }
235     stats.hashSerialized = ss.GetHash();
236     stats.nTotalAmount = nTotalAmount;
237     return true;
238 }
239
240 bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
241     CLevelDBBatch batch;
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);
244     }
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));
248     }
249     return WriteBatch(batch, true);
250 }
251
252 bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
253     return Read(make_pair(DB_TXINDEX, txid), pos);
254 }
255
256 bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
257     CLevelDBBatch batch;
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);
261 }
262
263 bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
264     return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
265 }
266
267 bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
268     char ch;
269     if (!Read(std::make_pair(DB_FLAG, name), ch))
270         return false;
271     fValue = ch == '1';
272     return true;
273 }
274
275 bool CBlockTreeDB::LoadBlockIndexGuts()
276 {
277     boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
278
279     CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
280     ssKeySet << make_pair(DB_BLOCK_INDEX, uint256());
281     pcursor->Seek(ssKeySet.str());
282
283     // Load mapBlockIndex
284     while (pcursor->Valid()) {
285         boost::this_thread::interruption_point();
286         try {
287             leveldb::Slice slKey = pcursor->key();
288             CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
289             char chType;
290             ssKey >> chType;
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;
296
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;
313
314                 if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
315                     return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
316
317                 pcursor->Next();
318             } else {
319                 break; // if shutdown requested or finished loading block index
320             }
321         } catch (const std::exception& e) {
322             return error("%s: Deserialize or I/O error - %s", __func__, e.what());
323         }
324     }
325
326     return true;
327 }
This page took 0.040143 seconds and 4 git commands to generate.