]> Git Repo - VerusCoin.git/blob - src/txdb.cpp
Rename Merkle Trees to include sprout or sapling
[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 // 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';
30
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';
37
38
39 CCoinsViewDB::CCoinsViewDB(std::string dbName, size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / dbName, nCacheSize, fMemory, fWipe) {
40 }
41
42 CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) 
43 {
44 }
45
46
47 bool CCoinsViewDB::GetSproutAnchorAt(const uint256 &rt, SproutMerkleTree &tree) const {
48     if (rt == SproutMerkleTree::empty_root()) {
49         SproutMerkleTree new_tree;
50         tree = new_tree;
51         return true;
52     }
53
54     bool read = db.Read(make_pair(DB_SPROUT_ANCHOR, rt), tree);
55
56     return read;
57 }
58
59 bool CCoinsViewDB::GetSaplingAnchorAt(const uint256 &rt, SaplingMerkleTree &tree) const {
60     if (rt == SaplingMerkleTree::empty_root()) {
61         SaplingMerkleTree new_tree;
62         tree = new_tree;
63         return true;
64     }
65
66     bool read = db.Read(make_pair(DB_SAPLING_ANCHOR, rt), tree);
67
68     return read;
69 }
70
71 bool CCoinsViewDB::GetNullifier(const uint256 &nf, ShieldedType type) const {
72     bool spent = false;
73     char dbChar;
74     switch (type) {
75         case SPROUT:
76             dbChar = DB_NULLIFIER;
77             break;
78         case SAPLING:
79             dbChar = DB_SAPLING_NULLIFIER;
80             break;
81         default:
82             throw runtime_error("Unknown shielded type");
83     }
84     return db.Read(make_pair(dbChar, nf), spent);
85 }
86
87 bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
88     return db.Read(make_pair(DB_COINS, txid), coins);
89 }
90
91 bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
92     return db.Exists(make_pair(DB_COINS, txid));
93 }
94
95 uint256 CCoinsViewDB::GetBestBlock() const {
96     uint256 hashBestChain;
97     if (!db.Read(DB_BEST_BLOCK, hashBestChain))
98         return uint256();
99     return hashBestChain;
100 }
101
102 uint256 CCoinsViewDB::GetBestAnchor(ShieldedType type) const {
103     uint256 hashBestAnchor;
104     
105     switch (type) {
106         case SPROUT:
107             if (!db.Read(DB_BEST_SPROUT_ANCHOR, hashBestAnchor))
108                 return SproutMerkleTree::empty_root();
109             break;
110         case SAPLING:
111             if (!db.Read(DB_BEST_SAPLING_ANCHOR, hashBestAnchor))
112                 return SaplingMerkleTree::empty_root();
113             break;
114         default:
115             throw runtime_error("Unknown shielded type");
116     }
117
118     return hashBestAnchor;
119 }
120
121 void BatchWriteNullifiers(CDBBatch& batch, CNullifiersMap& mapToUse, const char& dbChar)
122 {
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));
127             else
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
130         }
131         CNullifiersMap::iterator itOld = it++;
132         mapToUse.erase(itOld);
133     }
134 }
135
136 template<typename Map, typename MapIterator, typename MapEntry, typename Tree>
137 void BatchWriteAnchors(CDBBatch& batch, Map& mapToUse, const char& dbChar)
138 {
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));
143             else {
144                 if (it->first != Tree::empty_root()) {
145                     batch.Write(make_pair(dbChar, it->first), it->second.tree);
146                 }
147             }
148             // TODO: changed++?
149         }
150         MapIterator itOld = it++;
151         mapToUse.erase(itOld);
152     }
153 }
154
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) {
163     CDBBatch batch(db);
164     size_t count = 0;
165     size_t changed = 0;
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));
170             else
171                 batch.Write(make_pair(DB_COINS, it->first), it->second.coins);
172             changed++;
173         }
174         count++;
175         CCoinsMap::iterator itOld = it++;
176         mapCoins.erase(itOld);
177     }
178
179     ::BatchWriteAnchors<CAnchorsSproutMap, CAnchorsSproutMap::iterator, CAnchorsSproutCacheEntry, SproutMerkleTree>(batch, mapSproutAnchors, DB_SPROUT_ANCHOR);
180     ::BatchWriteAnchors<CAnchorsSaplingMap, CAnchorsSaplingMap::iterator, CAnchorsSaplingCacheEntry, SaplingMerkleTree>(batch, mapSaplingAnchors, DB_SAPLING_ANCHOR);
181
182     ::BatchWriteNullifiers(batch, mapSproutNullifiers, DB_NULLIFIER);
183     ::BatchWriteNullifiers(batch, mapSaplingNullifiers, DB_SAPLING_NULLIFIER);
184
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);
191
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);
194 }
195
196 CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
197 }
198
199 bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
200     return Read(make_pair(DB_BLOCK_FILES, nFile), info);
201 }
202
203 bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
204     if (fReindexing)
205         return Write(DB_REINDEX_FLAG, '1');
206     else
207         return Erase(DB_REINDEX_FLAG);
208 }
209
210 bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
211     fReindexing = Exists(DB_REINDEX_FLAG);
212     return true;
213 }
214
215 bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
216     return Read(DB_LAST_BLOCK, nFile);
217 }
218
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
222        that restriction.  */
223     boost::scoped_ptr<CDBIterator> pcursor(const_cast<CDBWrapper*>(&db)->NewIterator());
224     pcursor->Seek(DB_COINS);
225
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;
233         CCoins coins;
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];
239                     if (!out.IsNull()) {
240                         stats.nTransactionOutputs++;
241                         ss << VARINT(i+1);
242                         ss << out;
243                         nTotalAmount += out.nValue;
244                     }
245                 }
246                 stats.nSerializedSize += 32 + pcursor->GetValueSize();
247                 ss << VARINT(0);
248             } else {
249                 return error("CCoinsViewDB::GetStats() : unable to read value");
250             }
251         } else {
252             break;
253         }
254         pcursor->Next();
255     }
256     {
257         LOCK(cs_main);
258         stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
259     }
260     stats.hashSerialized = ss.GetHash();
261     stats.nTotalAmount = nTotalAmount;
262     return true;
263 }
264
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);
269     }
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));
273     }
274     return WriteBatch(batch, true);
275 }
276
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()));
281     }
282     return WriteBatch(batch, true);
283 }
284
285 bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
286     return Read(make_pair(DB_TXINDEX, txid), pos);
287 }
288
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);
294 }
295
296 bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
297     return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
298 }
299
300 bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
301     char ch;
302     if (!Read(std::make_pair(DB_FLAG, name), ch))
303         return false;
304     fValue = ch == '1';
305     return true;
306 }
307
308 bool CBlockTreeDB::LoadBlockIndexGuts()
309 {
310     boost::scoped_ptr<CDBIterator> pcursor(NewIterator());
311
312     pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));
313
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;
340
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());
348
349                 pcursor->Next();
350             } else {
351                 return error("LoadBlockIndex() : failed to read value");
352             }
353         } else {
354             break;
355         }
356     }
357
358     return true;
359 }
This page took 0.044543 seconds and 4 git commands to generate.