Dash Core  0.12.2.1
P2P Digital Currency
txdb.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 "chain.h"
9 #include "chainparams.h"
10 #include "hash.h"
11 #include "validation.h"
12 #include "pow.h"
13 #include "uint256.h"
14 
15 #include <stdint.h>
16 
17 #include <boost/thread.hpp>
18 
19 using namespace std;
20 
21 static const char DB_COINS = 'c';
22 static const char DB_BLOCK_FILES = 'f';
23 static const char DB_TXINDEX = 't';
24 static const char DB_ADDRESSINDEX = 'a';
25 static const char DB_ADDRESSUNSPENTINDEX = 'u';
26 static const char DB_TIMESTAMPINDEX = 's';
27 static const char DB_SPENTINDEX = 'p';
28 static const char DB_BLOCK_INDEX = 'b';
29 
30 static const char DB_BEST_BLOCK = 'B';
31 static const char DB_FLAG = 'F';
32 static const char DB_REINDEX_FLAG = 'R';
33 static const char DB_LAST_BLOCK = 'l';
34 
35 
36 CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true)
37 {
38 }
39 
40 bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
41  return db.Read(make_pair(DB_COINS, txid), coins);
42 }
43 
44 bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
45  return db.Exists(make_pair(DB_COINS, txid));
46 }
47 
49  uint256 hashBestChain;
50  if (!db.Read(DB_BEST_BLOCK, hashBestChain))
51  return uint256();
52  return hashBestChain;
53 }
54 
55 bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
56  CDBBatch batch(&db.GetObfuscateKey());
57  size_t count = 0;
58  size_t changed = 0;
59  for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
60  if (it->second.flags & CCoinsCacheEntry::DIRTY) {
61  if (it->second.coins.IsPruned())
62  batch.Erase(make_pair(DB_COINS, it->first));
63  else
64  batch.Write(make_pair(DB_COINS, it->first), it->second.coins);
65  changed++;
66  }
67  count++;
68  CCoinsMap::iterator itOld = it++;
69  mapCoins.erase(itOld);
70  }
71  if (!hashBlock.IsNull())
72  batch.Write(DB_BEST_BLOCK, hashBlock);
73 
74  LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
75  return db.WriteBatch(batch);
76 }
77 
78 CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
79 }
80 
82  return Read(make_pair(DB_BLOCK_FILES, nFile), info);
83 }
84 
85 bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
86  if (fReindexing)
87  return Write(DB_REINDEX_FLAG, '1');
88  else
89  return Erase(DB_REINDEX_FLAG);
90 }
91 
92 bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
93  fReindexing = Exists(DB_REINDEX_FLAG);
94  return true;
95 }
96 
98  return Read(DB_LAST_BLOCK, nFile);
99 }
100 
102  /* It seems that there are no "const iterators" for LevelDB. Since we
103  only need read operations on it, use a const-cast to get around
104  that restriction. */
105  boost::scoped_ptr<CDBIterator> pcursor(const_cast<CDBWrapper*>(&db)->NewIterator());
106  pcursor->Seek(DB_COINS);
107 
109  stats.hashBlock = GetBestBlock();
110  ss << stats.hashBlock;
111  CAmount nTotalAmount = 0;
112  while (pcursor->Valid()) {
113  boost::this_thread::interruption_point();
114  std::pair<char, uint256> key;
115  CCoins coins;
116  if (pcursor->GetKey(key) && key.first == DB_COINS) {
117  if (pcursor->GetValue(coins)) {
118  stats.nTransactions++;
119  for (unsigned int i=0; i<coins.vout.size(); i++) {
120  const CTxOut &out = coins.vout[i];
121  if (!out.IsNull()) {
122  stats.nTransactionOutputs++;
123  ss << VARINT(i+1);
124  ss << out;
125  nTotalAmount += out.nValue;
126  }
127  }
128  stats.nSerializedSize += 32 + pcursor->GetValueSize();
129  ss << VARINT(0);
130  } else {
131  return error("CCoinsViewDB::GetStats() : unable to read value");
132  }
133  } else {
134  break;
135  }
136  pcursor->Next();
137  }
138  {
139  LOCK(cs_main);
140  stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
141  }
142  stats.hashSerialized = ss.GetHash();
143  stats.nTotalAmount = nTotalAmount;
144  return true;
145 }
146 
147 bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
148  CDBBatch batch(&GetObfuscateKey());
149  for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
150  batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
151  }
152  batch.Write(DB_LAST_BLOCK, nLastFile);
153  for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
154  batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
155  }
156  return WriteBatch(batch, true);
157 }
158 
160  return Read(make_pair(DB_TXINDEX, txid), pos);
161 }
162 
163 bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
164  CDBBatch batch(&GetObfuscateKey());
165  for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
166  batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
167  return WriteBatch(batch);
168 }
169 
171  return Read(make_pair(DB_SPENTINDEX, key), value);
172 }
173 
174 bool CBlockTreeDB::UpdateSpentIndex(const std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> >&vect) {
175  CDBBatch batch(&GetObfuscateKey());
176  for (std::vector<std::pair<CSpentIndexKey,CSpentIndexValue> >::const_iterator it=vect.begin(); it!=vect.end(); it++) {
177  if (it->second.IsNull()) {
178  batch.Erase(make_pair(DB_SPENTINDEX, it->first));
179  } else {
180  batch.Write(make_pair(DB_SPENTINDEX, it->first), it->second);
181  }
182  }
183  return WriteBatch(batch);
184 }
185 
186 bool CBlockTreeDB::UpdateAddressUnspentIndex(const std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue > >&vect) {
187  CDBBatch batch(&GetObfuscateKey());
188  for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=vect.begin(); it!=vect.end(); it++) {
189  if (it->second.IsNull()) {
190  batch.Erase(make_pair(DB_ADDRESSUNSPENTINDEX, it->first));
191  } else {
192  batch.Write(make_pair(DB_ADDRESSUNSPENTINDEX, it->first), it->second);
193  }
194  }
195  return WriteBatch(batch);
196 }
197 
199  std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs) {
200 
201  boost::scoped_ptr<CDBIterator> pcursor(NewIterator());
202 
203  pcursor->Seek(make_pair(DB_ADDRESSUNSPENTINDEX, CAddressIndexIteratorKey(type, addressHash)));
204 
205  while (pcursor->Valid()) {
206  boost::this_thread::interruption_point();
207  std::pair<char,CAddressUnspentKey> key;
208  if (pcursor->GetKey(key) && key.first == DB_ADDRESSUNSPENTINDEX && key.second.hashBytes == addressHash) {
209  CAddressUnspentValue nValue;
210  if (pcursor->GetValue(nValue)) {
211  unspentOutputs.push_back(make_pair(key.second, nValue));
212  pcursor->Next();
213  } else {
214  return error("failed to get address unspent value");
215  }
216  } else {
217  break;
218  }
219  }
220 
221  return true;
222 }
223 
224 bool CBlockTreeDB::WriteAddressIndex(const std::vector<std::pair<CAddressIndexKey, CAmount > >&vect) {
225  CDBBatch batch(&GetObfuscateKey());
226  for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
227  batch.Write(make_pair(DB_ADDRESSINDEX, it->first), it->second);
228  return WriteBatch(batch);
229 }
230 
231 bool CBlockTreeDB::EraseAddressIndex(const std::vector<std::pair<CAddressIndexKey, CAmount > >&vect) {
232  CDBBatch batch(&GetObfuscateKey());
233  for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
234  batch.Erase(make_pair(DB_ADDRESSINDEX, it->first));
235  return WriteBatch(batch);
236 }
237 
238 bool CBlockTreeDB::ReadAddressIndex(uint160 addressHash, int type,
239  std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex,
240  int start, int end) {
241 
242  boost::scoped_ptr<CDBIterator> pcursor(NewIterator());
243 
244  if (start > 0 && end > 0) {
245  pcursor->Seek(make_pair(DB_ADDRESSINDEX, CAddressIndexIteratorHeightKey(type, addressHash, start)));
246  } else {
247  pcursor->Seek(make_pair(DB_ADDRESSINDEX, CAddressIndexIteratorKey(type, addressHash)));
248  }
249 
250  while (pcursor->Valid()) {
251  boost::this_thread::interruption_point();
252  std::pair<char,CAddressIndexKey> key;
253  if (pcursor->GetKey(key) && key.first == DB_ADDRESSINDEX && key.second.hashBytes == addressHash) {
254  if (end > 0 && key.second.blockHeight > end) {
255  break;
256  }
257  CAmount nValue;
258  if (pcursor->GetValue(nValue)) {
259  addressIndex.push_back(make_pair(key.second, nValue));
260  pcursor->Next();
261  } else {
262  return error("failed to get address index value");
263  }
264  } else {
265  break;
266  }
267  }
268 
269  return true;
270 }
271 
273  CDBBatch batch(&GetObfuscateKey());
274  batch.Write(make_pair(DB_TIMESTAMPINDEX, timestampIndex), 0);
275  return WriteBatch(batch);
276 }
277 
278 bool CBlockTreeDB::ReadTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector<uint256> &hashes) {
279 
280  boost::scoped_ptr<CDBIterator> pcursor(NewIterator());
281 
282  pcursor->Seek(make_pair(DB_TIMESTAMPINDEX, CTimestampIndexIteratorKey(low)));
283 
284  while (pcursor->Valid()) {
285  boost::this_thread::interruption_point();
286  std::pair<char, CTimestampIndexKey> key;
287  if (pcursor->GetKey(key) && key.first == DB_TIMESTAMPINDEX && key.second.timestamp <= high) {
288  hashes.push_back(key.second.blockHash);
289  pcursor->Next();
290  } else {
291  break;
292  }
293  }
294 
295  return true;
296 }
297 
298 bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
299  return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
300 }
301 
302 bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
303  char ch;
304  if (!Read(std::make_pair(DB_FLAG, name), ch))
305  return false;
306  fValue = ch == '1';
307  return true;
308 }
309 
311 {
312  boost::scoped_ptr<CDBIterator> pcursor(NewIterator());
313 
314  pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));
315 
316  // Load mapBlockIndex
317  while (pcursor->Valid()) {
318  boost::this_thread::interruption_point();
319  std::pair<char, uint256> key;
320  if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
321  CDiskBlockIndex diskindex;
322  if (pcursor->GetValue(diskindex)) {
323  // Construct block index object
324  CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
325  pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
326  pindexNew->nHeight = diskindex.nHeight;
327  pindexNew->nFile = diskindex.nFile;
328  pindexNew->nDataPos = diskindex.nDataPos;
329  pindexNew->nUndoPos = diskindex.nUndoPos;
330  pindexNew->nVersion = diskindex.nVersion;
331  pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
332  pindexNew->nTime = diskindex.nTime;
333  pindexNew->nBits = diskindex.nBits;
334  pindexNew->nNonce = diskindex.nNonce;
335  pindexNew->nStatus = diskindex.nStatus;
336  pindexNew->nTx = diskindex.nTx;
337 
338  if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
339  return error("%s: CheckProofOfWork failed: %s", __func__, pindexNew->ToString());
340 
341  pcursor->Next();
342  } else {
343  return error("%s: failed to read value", __func__);
344  }
345  } else {
346  break;
347  }
348  }
349 
350  return true;
351 }
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:547
static const char DB_LAST_BLOCK
Definition: txdb.cpp:33
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
Definition: txdb.cpp:81
#define VARINT(obj)
Definition: serialize.h:388
bool HaveCoins(const uint256 &txid) const
Definition: txdb.cpp:44
Definition: coins.h:73
CAmount nTotalAmount
Definition: coins.h:308
static const char DB_TIMESTAMPINDEX
Definition: txdb.cpp:26
static const char DB_BEST_BLOCK
Definition: txdb.cpp:30
uint256 hashPrev
Definition: chain.h:288
uint256 hashSerialized
Definition: coins.h:307
CBlockTreeDB(size_t nCacheSize, bool fMemory=false, bool fWipe=false)
Definition: txdb.cpp:78
unsigned int nBits
Definition: chain.h:143
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:55
bool ReadAddressUnspentIndex(uint160 addressHash, int type, std::vector< std::pair< CAddressUnspentKey, CAddressUnspentValue > > &vect)
Definition: txdb.cpp:198
uint64_t nTransactionOutputs
Definition: coins.h:305
unsigned int nUndoPos
Byte offset within rev?????.dat where this block&#39;s undo data is stored.
Definition: chain.h:122
CCriticalSection cs_main
Definition: validation.cpp:62
CDBWrapper db
Definition: txdb.h:42
sph_u32 high
Definition: keccak.c:370
bool ReadAddressIndex(uint160 addressHash, int type, std::vector< std::pair< CAddressIndexKey, CAmount > > &addressIndex, int start=0, int end=0)
Definition: txdb.cpp:238
bool WriteTxIndex(const std::vector< std::pair< uint256, CDiskTxPos > > &list)
Definition: txdb.cpp:163
static const char DB_ADDRESSUNSPENTINDEX
Definition: txdb.cpp:25
unsigned int nNonce
Definition: chain.h:144
boost::unordered_map< uint256, CCoinsCacheEntry, CCoinsKeyHasher > CCoinsMap
Definition: coins.h:298
unsigned int nTx
Definition: chain.h:129
bool WriteFlag(const std::string &name, bool fValue)
Definition: txdb.cpp:298
std::string ToString() const
Definition: chain.h:244
bool IsNull() const
Definition: uint256.h:33
bool Write(const K &key, const V &value, bool fSync=false)
Definition: dbwrapper.h:209
static const char DB_ADDRESSINDEX
Definition: txdb.cpp:24
uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: txdb.cpp:48
void Erase(const K &key)
Definition: dbwrapper.h:61
int64_t CAmount
Definition: amount.h:14
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: txdb.cpp:40
int nHeight
Definition: coins.h:302
uint256 GetHash()
Definition: hash.h:254
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock)
Definition: txdb.cpp:55
static const char DB_BLOCK_FILES
Definition: txdb.cpp:22
std::vector< CTxOut > vout
unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are d...
Definition: coins.h:80
static const char DB_FLAG
Definition: txdb.cpp:31
static int LogPrint(const char *category, const char *format)
Definition: util.h:126
#define LOCK(cs)
Definition: sync.h:168
const char * name
Definition: rest.cpp:37
uint256 hashMerkleRoot
Definition: chain.h:141
bool ReadSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
Definition: txdb.cpp:170
static bool error(const char *format)
Definition: util.h:131
bool WriteBatch(CDBBatch &batch, bool fSync=false)
Definition: dbwrapper.cpp:105
unsigned int nTime
Definition: chain.h:142
void Write(const K &key, const V &value)
Definition: dbwrapper.h:44
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
Definition: txdb.cpp:159
uint256 hashBlock
Definition: coins.h:303
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:116
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo *> > &fileInfo, int nLastFile, const std::vector< const CBlockIndex *> &blockinfo)
Definition: txdb.cpp:147
uint256 GetBlockHash() const
Definition: chain.h:328
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Definition: pow.cpp:238
CCoinsViewDB(size_t nCacheSize, bool fMemory=false, bool fWipe=false)
Definition: txdb.cpp:36
static const char DB_BLOCK_INDEX
Definition: txdb.cpp:28
bool WriteTimestampIndex(const CTimestampIndexKey &timestampIndex)
Definition: txdb.cpp:272
bool GetStats(CCoinsStats &stats) const
Calculate statistics about the unspent transaction output set.
Definition: txdb.cpp:101
bool UpdateAddressUnspentIndex(const std::vector< std::pair< CAddressUnspentKey, CAddressUnspentValue > > &vect)
Definition: txdb.cpp:186
bool ReadTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector< uint256 > &vect)
Definition: txdb.cpp:278
bool EraseAddressIndex(const std::vector< std::pair< CAddressIndexKey, CAmount > > &vect)
Definition: txdb.cpp:231
uint64_t nSerializedSize
Definition: coins.h:306
bool LoadBlockIndexGuts()
Definition: txdb.cpp:310
const CChainParams & Params()
static const int PROTOCOL_VERSION
Definition: version.h:13
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:137
bool Exists(const K &key) const
Definition: dbwrapper.h:217
uint256 GetBlockHash() const
Definition: chain.h:218
sph_u32 low
Definition: keccak.c:370
bool ReadReindexing(bool &fReindex)
Definition: txdb.cpp:92
bool ReadLastBlockFile(int &nFile)
Definition: txdb.cpp:97
static int count
Definition: tests.c:41
uint64_t nTransactions
Definition: coins.h:304
bool ReadFlag(const std::string &name, bool &fValue)
Definition: txdb.cpp:302
CDBIterator * NewIterator()
Definition: dbwrapper.h:257
bool Erase(const K &key, bool fSync=false)
Definition: dbwrapper.h:236
const std::vector< unsigned char > & GetObfuscateKey() const
Definition: dbwrapper.cpp:139
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:107
bool WriteAddressIndex(const std::vector< std::pair< CAddressIndexKey, CAmount > > &vect)
Definition: txdb.cpp:224
CBlockIndex * InsertBlockIndex(uint256 hash)
static const char DB_TXINDEX
Definition: txdb.cpp:23
unsigned int nDataPos
Byte offset within blk?????.dat where this block&#39;s data is stored.
Definition: chain.h:119
static const char DB_REINDEX_FLAG
Definition: txdb.cpp:32
static const char DB_COINS
Definition: txdb.cpp:21
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:113
int nVersion
block header
Definition: chain.h:140
bool Read(const K &key, V &value) const
Definition: dbwrapper.h:183
bool WriteReindexing(bool fReindex)
Definition: txdb.cpp:85
BlockMap mapBlockIndex
Definition: validation.cpp:64
bool UpdateSpentIndex(const std::vector< std::pair< CSpentIndexKey, CSpentIndexValue > > &vect)
Definition: txdb.cpp:174
static const char DB_SPENTINDEX
Definition: txdb.cpp:27