You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

txdb.cpp 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "txdb.h"
  6. #include "main.h"
  7. #include "hash.h"
  8. #include "chainparams.h"
  9. using namespace std;
  10. void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
  11. if (coins.IsPruned())
  12. batch.Erase(make_pair('c', hash));
  13. else
  14. batch.Write(make_pair('c', hash), coins);
  15. }
  16. void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
  17. batch.Write('B', hash);
  18. }
  19. CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
  20. }
  21. bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) {
  22. return db.Read(make_pair('c', txid), coins);
  23. }
  24. bool CCoinsViewDB::SetCoins(const uint256 &txid, const CCoins &coins) {
  25. CLevelDBBatch batch;
  26. BatchWriteCoins(batch, txid, coins);
  27. return db.WriteBatch(batch);
  28. }
  29. bool CCoinsViewDB::HaveCoins(const uint256 &txid) {
  30. return db.Exists(make_pair('c', txid));
  31. }
  32. CBlockIndex *CCoinsViewDB::GetBestBlock() {
  33. uint256 hashBestChain;
  34. if (!db.Read('B', hashBestChain))
  35. return NULL;
  36. std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(hashBestChain);
  37. if (it == mapBlockIndex.end())
  38. return NULL;
  39. return it->second;
  40. }
  41. bool CCoinsViewDB::SetBestBlock(CBlockIndex *pindex) {
  42. CLevelDBBatch batch;
  43. BatchWriteHashBestChain(batch, pindex->GetBlockHash());
  44. return db.WriteBatch(batch);
  45. }
  46. bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
  47. printf("Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());
  48. CLevelDBBatch batch;
  49. for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
  50. BatchWriteCoins(batch, it->first, it->second);
  51. if (pindex)
  52. BatchWriteHashBestChain(batch, pindex->GetBlockHash());
  53. return db.WriteBatch(batch);
  54. }
  55. CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDB(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
  56. }
  57. bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
  58. {
  59. return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
  60. }
  61. bool CBlockTreeDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
  62. {
  63. return Read('I', bnBestInvalidWork);
  64. }
  65. bool CBlockTreeDB::WriteBestInvalidWork(const CBigNum& bnBestInvalidWork)
  66. {
  67. return Write('I', bnBestInvalidWork);
  68. }
  69. bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
  70. return Write(make_pair('f', nFile), info);
  71. }
  72. bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
  73. return Read(make_pair('f', nFile), info);
  74. }
  75. bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
  76. return Write('l', nFile);
  77. }
  78. bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
  79. if (fReindexing)
  80. return Write('R', '1');
  81. else
  82. return Erase('R');
  83. }
  84. bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
  85. fReindexing = Exists('R');
  86. return true;
  87. }
  88. bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
  89. return Read('l', nFile);
  90. }
  91. bool CCoinsViewDB::GetStats(CCoinsStats &stats) {
  92. leveldb::Iterator *pcursor = db.NewIterator();
  93. pcursor->SeekToFirst();
  94. CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
  95. stats.hashBlock = GetBestBlock()->GetBlockHash();
  96. ss << stats.hashBlock;
  97. int64 nTotalAmount = 0;
  98. while (pcursor->Valid()) {
  99. boost::this_thread::interruption_point();
  100. try {
  101. leveldb::Slice slKey = pcursor->key();
  102. CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
  103. char chType;
  104. ssKey >> chType;
  105. if (chType == 'c') {
  106. leveldb::Slice slValue = pcursor->value();
  107. CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
  108. CCoins coins;
  109. ssValue >> coins;
  110. uint256 txhash;
  111. ssKey >> txhash;
  112. ss << txhash;
  113. ss << VARINT(coins.nVersion);
  114. ss << (coins.fCoinBase ? 'c' : 'n');
  115. ss << VARINT(coins.nHeight);
  116. stats.nTransactions++;
  117. for (unsigned int i=0; i<coins.vout.size(); i++) {
  118. const CTxOut &out = coins.vout[i];
  119. if (!out.IsNull()) {
  120. stats.nTransactionOutputs++;
  121. ss << VARINT(i+1);
  122. ss << out;
  123. nTotalAmount += out.nValue;
  124. }
  125. }
  126. stats.nSerializedSize += 32 + slValue.size();
  127. ss << VARINT(0);
  128. }
  129. pcursor->Next();
  130. } catch (std::exception &e) {
  131. return error("%s() : deserialize error", __PRETTY_FUNCTION__);
  132. }
  133. }
  134. delete pcursor;
  135. stats.nHeight = GetBestBlock()->nHeight;
  136. stats.hashSerialized = ss.GetHash();
  137. stats.nTotalAmount = nTotalAmount;
  138. return true;
  139. }
  140. bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
  141. return Read(make_pair('t', txid), pos);
  142. }
  143. bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
  144. CLevelDBBatch batch;
  145. for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
  146. batch.Write(make_pair('t', it->first), it->second);
  147. return WriteBatch(batch);
  148. }
  149. bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
  150. return Write(std::make_pair('F', name), fValue ? '1' : '0');
  151. }
  152. bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
  153. char ch;
  154. if (!Read(std::make_pair('F', name), ch))
  155. return false;
  156. fValue = ch == '1';
  157. return true;
  158. }
  159. bool CBlockTreeDB::LoadBlockIndexGuts()
  160. {
  161. leveldb::Iterator *pcursor = NewIterator();
  162. CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
  163. ssKeySet << make_pair('b', uint256(0));
  164. pcursor->Seek(ssKeySet.str());
  165. // Load mapBlockIndex
  166. while (pcursor->Valid()) {
  167. boost::this_thread::interruption_point();
  168. try {
  169. leveldb::Slice slKey = pcursor->key();
  170. CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
  171. char chType;
  172. ssKey >> chType;
  173. if (chType == 'b') {
  174. leveldb::Slice slValue = pcursor->value();
  175. CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
  176. CDiskBlockIndex diskindex;
  177. ssValue >> diskindex;
  178. // Construct block index object
  179. CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
  180. pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
  181. pindexNew->nHeight = diskindex.nHeight;
  182. pindexNew->nFile = diskindex.nFile;
  183. pindexNew->nDataPos = diskindex.nDataPos;
  184. pindexNew->nUndoPos = diskindex.nUndoPos;
  185. pindexNew->nVersion = diskindex.nVersion;
  186. pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
  187. pindexNew->nTime = diskindex.nTime;
  188. pindexNew->nBits = diskindex.nBits;
  189. pindexNew->nNonce = diskindex.nNonce;
  190. pindexNew->nStatus = diskindex.nStatus;
  191. pindexNew->nTx = diskindex.nTx;
  192. // Watch for genesis block
  193. if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == Params().HashGenesisBlock())
  194. pindexGenesisBlock = pindexNew;
  195. if (!pindexNew->CheckIndex())
  196. return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString().c_str());
  197. pcursor->Next();
  198. } else {
  199. break; // if shutdown requested or finished loading block index
  200. }
  201. } catch (std::exception &e) {
  202. return error("%s() : deserialize error", __PRETTY_FUNCTION__);
  203. }
  204. }
  205. delete pcursor;
  206. return true;
  207. }