BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
txdb.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 <random.h>
11 #include <pow.h>
12 #include <shutdown.h>
13 #include <uint256.h>
14 #include <util.h>
15 #include <ui_interface.h>
16 
17 #include <stdint.h>
18 
19 #include <boost/thread.hpp>
20 
21 static const char DB_COIN = 'C';
22 static const char DB_COINS = 'c';
23 static const char DB_BLOCK_FILES = 'f';
24 static const char DB_BLOCK_INDEX = 'b';
25 
26 static const char DB_BEST_BLOCK = 'B';
27 static const char DB_HEAD_BLOCKS = 'H';
28 static const char DB_FLAG = 'F';
29 static const char DB_REINDEX_FLAG = 'R';
30 static const char DB_LAST_BLOCK = 'l';
31 
32 namespace {
33 
34 struct CoinEntry {
35  COutPoint* outpoint;
36  char key;
37  explicit CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {}
38 
39  template<typename Stream>
40  void Serialize(Stream &s) const {
41  s << key;
42  s << outpoint->hash;
43  s << VARINT(outpoint->n);
44  }
45 
46  template<typename Stream>
47  void Unserialize(Stream& s) {
48  s >> key;
49  s >> outpoint->hash;
50  s >> VARINT(outpoint->n);
51  }
52 };
53 
54 }
55 
56 CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true)
57 {
58 }
59 
60 bool CCoinsViewDB::GetCoin(const COutPoint &outpoint, Coin &coin) const {
61  return db.Read(CoinEntry(&outpoint), coin);
62 }
63 
64 bool CCoinsViewDB::HaveCoin(const COutPoint &outpoint) const {
65  return db.Exists(CoinEntry(&outpoint));
66 }
67 
69  uint256 hashBestChain;
70  if (!db.Read(DB_BEST_BLOCK, hashBestChain))
71  return uint256();
72  return hashBestChain;
73 }
74 
75 std::vector<uint256> CCoinsViewDB::GetHeadBlocks() const {
76  std::vector<uint256> vhashHeadBlocks;
77  if (!db.Read(DB_HEAD_BLOCKS, vhashHeadBlocks)) {
78  return std::vector<uint256>();
79  }
80  return vhashHeadBlocks;
81 }
82 
83 bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
84  CDBBatch batch(db);
85  size_t count = 0;
86  size_t changed = 0;
87  size_t batch_size = (size_t)gArgs.GetArg("-dbbatchsize", nDefaultDbBatchSize);
88  int crash_simulate = gArgs.GetArg("-dbcrashratio", 0);
89  assert(!hashBlock.IsNull());
90 
91  uint256 old_tip = GetBestBlock();
92  if (old_tip.IsNull()) {
93  // We may be in the middle of replaying.
94  std::vector<uint256> old_heads = GetHeadBlocks();
95  if (old_heads.size() == 2) {
96  assert(old_heads[0] == hashBlock);
97  old_tip = old_heads[1];
98  }
99  }
100 
101  // In the first batch, mark the database as being in the middle of a
102  // transition from old_tip to hashBlock.
103  // A vector is used for future extensibility, as we may want to support
104  // interrupting after partial writes from multiple independent reorgs.
105  batch.Erase(DB_BEST_BLOCK);
106  batch.Write(DB_HEAD_BLOCKS, std::vector<uint256>{hashBlock, old_tip});
107 
108  for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
109  if (it->second.flags & CCoinsCacheEntry::DIRTY) {
110  CoinEntry entry(&it->first);
111  if (it->second.coin.IsSpent())
112  batch.Erase(entry);
113  else
114  batch.Write(entry, it->second.coin);
115  changed++;
116  }
117  count++;
118  CCoinsMap::iterator itOld = it++;
119  mapCoins.erase(itOld);
120  if (batch.SizeEstimate() > batch_size) {
121  LogPrint(BCLog::COINDB, "Writing partial batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0));
122  db.WriteBatch(batch);
123  batch.Clear();
124  if (crash_simulate) {
125  static FastRandomContext rng;
126  if (rng.randrange(crash_simulate) == 0) {
127  LogPrintf("Simulating a crash. Goodbye.\n");
128  _Exit(0);
129  }
130  }
131  }
132  }
133 
134  // In the last batch, mark the database as consistent with hashBlock again.
135  batch.Erase(DB_HEAD_BLOCKS);
136  batch.Write(DB_BEST_BLOCK, hashBlock);
137 
138  LogPrint(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0));
139  bool ret = db.WriteBatch(batch);
140  LogPrint(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
141  return ret;
142 }
143 
145 {
146  return db.EstimateSize(DB_COIN, (char)(DB_COIN+1));
147 }
148 
149 CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(gArgs.IsArgSet("-blocksdir") ? GetDataDir() / "blocks" / "index" : GetBlocksDir() / "index", nCacheSize, fMemory, fWipe) {
150 }
151 
153  return Read(std::make_pair(DB_BLOCK_FILES, nFile), info);
154 }
155 
156 bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
157  if (fReindexing)
158  return Write(DB_REINDEX_FLAG, '1');
159  else
160  return Erase(DB_REINDEX_FLAG);
161 }
162 
163 void CBlockTreeDB::ReadReindexing(bool &fReindexing) {
164  fReindexing = Exists(DB_REINDEX_FLAG);
165 }
166 
168  return Read(DB_LAST_BLOCK, nFile);
169 }
170 
172 {
173  CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper&>(db).NewIterator(), GetBestBlock());
174  /* It seems that there are no "const iterators" for LevelDB. Since we
175  only need read operations on it, use a const-cast to get around
176  that restriction. */
177  i->pcursor->Seek(DB_COIN);
178  // Cache key of first record
179  if (i->pcursor->Valid()) {
180  CoinEntry entry(&i->keyTmp.second);
181  i->pcursor->GetKey(entry);
182  i->keyTmp.first = entry.key;
183  } else {
184  i->keyTmp.first = 0; // Make sure Valid() and GetKey() return false
185  }
186  return i;
187 }
188 
190 {
191  // Return cached key
192  if (keyTmp.first == DB_COIN) {
193  key = keyTmp.second;
194  return true;
195  }
196  return false;
197 }
198 
200 {
201  return pcursor->GetValue(coin);
202 }
203 
205 {
206  return pcursor->GetValueSize();
207 }
208 
210 {
211  return keyTmp.first == DB_COIN;
212 }
213 
215 {
216  pcursor->Next();
217  CoinEntry entry(&keyTmp.second);
218  if (!pcursor->Valid() || !pcursor->GetKey(entry)) {
219  keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false
220  } else {
221  keyTmp.first = entry.key;
222  }
223 }
224 
225 bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
226  CDBBatch batch(*this);
227  for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
228  batch.Write(std::make_pair(DB_BLOCK_FILES, it->first), *it->second);
229  }
230  batch.Write(DB_LAST_BLOCK, nLastFile);
231  for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
232  batch.Write(std::make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
233  }
234  return WriteBatch(batch, true);
235 }
236 
237 bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
238  return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
239 }
240 
241 bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
242  char ch;
243  if (!Read(std::make_pair(DB_FLAG, name), ch))
244  return false;
245  fValue = ch == '1';
246  return true;
247 }
248 
249 bool CBlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex)
250 {
251  std::unique_ptr<CDBIterator> pcursor(NewIterator());
252 
253  pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256()));
254 
255  // Load mapBlockIndex
256  while (pcursor->Valid()) {
257  boost::this_thread::interruption_point();
258  std::pair<char, uint256> key;
259  if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
260  CDiskBlockIndex diskindex;
261  if (pcursor->GetValue(diskindex)) {
262  // Construct block index object
263  CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash());
264  pindexNew->pprev = insertBlockIndex(diskindex.hashPrev);
265  pindexNew->nHeight = diskindex.nHeight;
266  pindexNew->nFile = diskindex.nFile;
267  pindexNew->nDataPos = diskindex.nDataPos;
268  pindexNew->nUndoPos = diskindex.nUndoPos;
269  pindexNew->nVersion = diskindex.nVersion;
270  pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
271  pindexNew->nTime = diskindex.nTime;
272  pindexNew->nBits = diskindex.nBits;
273  pindexNew->nNonce = diskindex.nNonce;
274  pindexNew->nStatus = diskindex.nStatus;
275  pindexNew->nTx = diskindex.nTx;
276 
277  if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, consensusParams))
278  return error("%s: CheckProofOfWork failed: %s", __func__, pindexNew->ToString());
279 
280  pcursor->Next();
281  } else {
282  return error("%s: failed to read value", __func__);
283  }
284  } else {
285  break;
286  }
287  }
288 
289  return true;
290 }
291 
292 namespace {
293 
295 class CCoins
296 {
297 public:
299  bool fCoinBase;
300 
302  std::vector<CTxOut> vout;
303 
305  int nHeight;
306 
308  CCoins() : fCoinBase(false), vout(0), nHeight(0) { }
309 
310  template<typename Stream>
311  void Unserialize(Stream &s) {
312  unsigned int nCode = 0;
313  // version
314  unsigned int nVersionDummy;
315  ::Unserialize(s, VARINT(nVersionDummy));
316  // header code
317  ::Unserialize(s, VARINT(nCode));
318  fCoinBase = nCode & 1;
319  std::vector<bool> vAvail(2, false);
320  vAvail[0] = (nCode & 2) != 0;
321  vAvail[1] = (nCode & 4) != 0;
322  unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
323  // spentness bitmask
324  while (nMaskCode > 0) {
325  unsigned char chAvail = 0;
326  ::Unserialize(s, chAvail);
327  for (unsigned int p = 0; p < 8; p++) {
328  bool f = (chAvail & (1 << p)) != 0;
329  vAvail.push_back(f);
330  }
331  if (chAvail != 0)
332  nMaskCode--;
333  }
334  // txouts themself
335  vout.assign(vAvail.size(), CTxOut());
336  for (unsigned int i = 0; i < vAvail.size(); i++) {
337  if (vAvail[i])
338  ::Unserialize(s, CTxOutCompressor(vout[i]));
339  }
340  // coinbase height
342  }
343 };
344 
345 }
346 
352  std::unique_ptr<CDBIterator> pcursor(db.NewIterator());
353  pcursor->Seek(std::make_pair(DB_COINS, uint256()));
354  if (!pcursor->Valid()) {
355  return true;
356  }
357 
358  int64_t count = 0;
359  LogPrintf("Upgrading utxo-set database...\n");
360  LogPrintf("[0%%]..."); /* Continued */
361  uiInterface.ShowProgress(_("Upgrading UTXO database"), 0, true);
362  size_t batch_size = 1 << 24;
363  CDBBatch batch(db);
364  int reportDone = 0;
365  std::pair<unsigned char, uint256> key;
366  std::pair<unsigned char, uint256> prev_key = {DB_COINS, uint256()};
367  while (pcursor->Valid()) {
368  boost::this_thread::interruption_point();
369  if (ShutdownRequested()) {
370  break;
371  }
372  if (pcursor->GetKey(key) && key.first == DB_COINS) {
373  if (count++ % 256 == 0) {
374  uint32_t high = 0x100 * *key.second.begin() + *(key.second.begin() + 1);
375  int percentageDone = (int)(high * 100.0 / 65536.0 + 0.5);
376  uiInterface.ShowProgress(_("Upgrading UTXO database"), percentageDone, true);
377  if (reportDone < percentageDone/10) {
378  // report max. every 10% step
379  LogPrintf("[%d%%]...", percentageDone); /* Continued */
380  reportDone = percentageDone/10;
381  }
382  }
383  CCoins old_coins;
384  if (!pcursor->GetValue(old_coins)) {
385  return error("%s: cannot parse CCoins record", __func__);
386  }
387  COutPoint outpoint(key.second, 0);
388  for (size_t i = 0; i < old_coins.vout.size(); ++i) {
389  if (!old_coins.vout[i].IsNull() && !old_coins.vout[i].scriptPubKey.IsUnspendable()) {
390  Coin newcoin(std::move(old_coins.vout[i]), old_coins.nHeight, old_coins.fCoinBase);
391  outpoint.n = i;
392  CoinEntry entry(&outpoint);
393  batch.Write(entry, newcoin);
394  }
395  }
396  batch.Erase(key);
397  if (batch.SizeEstimate() > batch_size) {
398  db.WriteBatch(batch);
399  batch.Clear();
400  db.CompactRange(prev_key, key);
401  prev_key = key;
402  }
403  pcursor->Next();
404  } else {
405  break;
406  }
407  }
408  db.WriteBatch(batch);
409  db.CompactRange({DB_COINS, uint256()}, key);
410  uiInterface.ShowProgress("", 100, false);
411  LogPrintf("[%s].\n", ShutdownRequested() ? "CANCELLED" : "DONE");
412  return !ShutdownRequested();
413 }
bool Exists(const K &key) const
Definition: dbwrapper.h:265
bool GetValue(Coin &coin) const override
Definition: txdb.cpp:199
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txdb.cpp:60
std::string ToString() const
Definition: chain.h:323
void Clear()
Definition: dbwrapper.h:66
bool ShutdownRequested()
Definition: shutdown.cpp:20
bool Upgrade()
Attempt to update from an older database format. Returns whether an error occurred.
Definition: txdb.cpp:351
Specialization of CCoinsViewCursor to iterate over a CCoinsViewDB.
Definition: txdb.h:64
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:177
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:47
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
A UTXO entry.
Definition: coins.h:29
bool ReadLastBlockFile(int &nFile)
Definition: txdb.cpp:167
wrapper for CTxOut that provides a more compact serialization
Definition: compressor.h:86
UniValue ret(UniValue::VARR)
Definition: rpcwallet.cpp:1140
void Erase(const K &key)
Definition: dbwrapper.h:98
std::unique_ptr< CDBIterator > pcursor
Definition: txdb.h:79
void ReadReindexing(bool &fReindexing)
Definition: txdb.cpp:163
uint64_t randrange(uint64_t range)
Generate a random integer in the range [0..range).
Definition: random.h:104
uint32_t nTime
Definition: chain.h:212
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:186
bool GetKey(COutPoint &key) const override
Definition: txdb.cpp:189
bool IsNull() const
Definition: uint256.h:32
bool WriteReindexing(bool fReindexing)
Definition: txdb.cpp:156
CDBIterator * NewIterator()
Definition: dbwrapper.h:308
Definition: coins.h:109
void Serialize(Stream &s, char a)
Definition: serialize.h:193
uint256 GetBlockHash() const
Definition: chain.h:292
bool Erase(const K &key, bool fSync=false)
Definition: dbwrapper.h:284
uint32_t nNonce
Definition: chain.h:214
unsigned int nDataPos
Byte offset within blk?????.dat where this block&#39;s data is stored.
Definition: chain.h:189
const char * name
Definition: rest.cpp:37
Fast randomness source.
Definition: random.h:45
uint32_t n
Definition: transaction.h:22
CDBWrapper db
Definition: txdb.h:47
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:122
uint256 hashMerkleRoot
Definition: chain.h:211
void Write(const K &key, const V &value)
Definition: dbwrapper.h:73
size_t SizeEstimate() const
Definition: dbwrapper.h:114
An output of a transaction.
Definition: transaction.h:131
Used to marshal pointers into hashes for db storage.
Definition: chain.h:370
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: txdb.cpp:144
Parameters that influence chain consensus.
Definition: params.h:40
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:75
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
std::pair< char, COutPoint > keyTmp
Definition: txdb.h:80
bool Read(const K &key, V &value) const
Definition: dbwrapper.h:231
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: txdb.cpp:64
bool ReadFlag(const std::string &name, bool &fValue)
Definition: txdb.cpp:241
CBlockTreeDB(size_t nCacheSize, bool fMemory=false, bool fWipe=false)
Definition: txdb.cpp:149
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo *> > &fileInfo, int nLastFile, const std::vector< const CBlockIndex *> &blockinfo)
Definition: txdb.cpp:225
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &info)
Definition: txdb.cpp:152
const fs::path & GetBlocksDir(bool fNetSpecific)
Definition: util.cpp:737
CCoinsViewDB(size_t nCacheSize, bool fMemory=false, bool fWipe=false)
Definition: txdb.cpp:56
unsigned int nUndoPos
Byte offset within rev?????.dat where this block&#39;s undo data is stored.
Definition: chain.h:192
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: txdb.cpp:68
int32_t nVersion
block header
Definition: chain.h:210
256-bit opaque blob.
Definition: uint256.h:122
uint256 hashPrev
Definition: chain.h:373
bool Write(const K &key, const V &value, bool fSync=false)
Definition: dbwrapper.h:257
ArgsManager gArgs
Definition: util.cpp:88
void CompactRange(const K &key_begin, const K &key_end) const
Compact a certain range of keys in the database.
Definition: dbwrapper.h:338
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:526
constexpr char DB_BEST_BLOCK
Definition: base.cpp:14
void Unserialize(Stream &s, char &a)
Definition: serialize.h:211
bool error(const char *fmt, const Args &... args)
Definition: util.h:59
bool LoadBlockIndexGuts(const Consensus::Params &consensusParams, std::function< CBlockIndex *(const uint256 &)> insertBlockIndex)
Definition: txdb.cpp:249
bool WriteFlag(const std::string &name, bool fValue)
Definition: txdb.cpp:237
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: txdb.cpp:83
void Next() override
Definition: txdb.cpp:214
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:766
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: txdb.cpp:171
bool WriteBatch(CDBBatch &batch, bool fSync=false)
Definition: dbwrapper.cpp:183
bool Valid() const override
Definition: txdb.cpp:209
CClientUIInterface uiInterface
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
uint256 GetBlockHash() const
Definition: chain.h:410
unsigned int GetValueSize() const override
Definition: txdb.cpp:204
size_t EstimateSize(const K &key_begin, const K &key_end) const
Definition: dbwrapper.h:319
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: txdb.cpp:75
uint32_t nBits
Definition: chain.h:213
#define VARINT(obj,...)
Definition: serialize.h:411
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:199
std::string _(const char *psz)
Translation function.
Definition: util.h:50
uint256 hash
Definition: transaction.h:21
Cursor for iterating over CoinsView state.
Definition: coins.h:125