Line data Source code
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 "chain.h"
9 : #include "chainparams.h"
10 : #include "hash.h"
11 : #include "main.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_BLOCK_INDEX = 'b';
25 :
26 : static const char DB_BEST_BLOCK = 'B';
27 : static const char DB_FLAG = 'F';
28 : static const char DB_REINDEX_FLAG = 'R';
29 : static const char DB_LAST_BLOCK = 'l';
30 :
31 :
32 595 : CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true)
33 : {
34 119 : }
35 :
36 35635 : bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
37 35635 : return db.Read(make_pair(DB_COINS, txid), coins);
38 : }
39 :
40 0 : bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
41 0 : return db.Exists(make_pair(DB_COINS, txid));
42 : }
43 :
44 212 : uint256 CCoinsViewDB::GetBestBlock() const {
45 : uint256 hashBestChain;
46 212 : if (!db.Read(DB_BEST_BLOCK, hashBestChain))
47 : return uint256();
48 114 : return hashBestChain;
49 : }
50 :
51 155 : bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
52 155 : CLevelDBBatch batch(db.GetObfuscateKey());
53 155 : size_t count = 0;
54 155 : size_t changed = 0;
55 6150 : for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
56 5840 : if (it->second.flags & CCoinsCacheEntry::DIRTY) {
57 5826 : if (it->second.coins.IsPruned())
58 624 : batch.Erase(make_pair(DB_COINS, it->first));
59 : else
60 16542 : batch.Write(make_pair(DB_COINS, it->first), it->second.coins);
61 5826 : changed++;
62 : }
63 5840 : count++;
64 11680 : CCoinsMap::iterator itOld = it++;
65 : mapCoins.erase(itOld);
66 : }
67 155 : if (!hashBlock.IsNull())
68 155 : batch.Write(DB_BEST_BLOCK, hashBlock);
69 :
70 155 : LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
71 155 : return db.WriteBatch(batch);
72 : }
73 :
74 714 : CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
75 119 : }
76 :
77 186 : bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
78 186 : return Read(make_pair(DB_BLOCK_FILES, nFile), info);
79 : }
80 :
81 2 : bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
82 2 : if (fReindexing)
83 1 : return Write(DB_REINDEX_FLAG, '1');
84 : else
85 1 : return Erase(DB_REINDEX_FLAG);
86 : }
87 :
88 93 : bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
89 93 : fReindexing = Exists(DB_REINDEX_FLAG);
90 93 : return true;
91 : }
92 :
93 93 : bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
94 93 : return Read(DB_LAST_BLOCK, nFile);
95 : }
96 :
97 0 : bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
98 : /* It seems that there are no "const iterators" for LevelDB. Since we
99 : only need read operations on it, use a const-cast to get around
100 : that restriction. */
101 0 : boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator());
102 0 : pcursor->SeekToFirst();
103 :
104 : CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
105 0 : stats.hashBlock = GetBestBlock();
106 0 : ss << stats.hashBlock;
107 : CAmount nTotalAmount = 0;
108 0 : while (pcursor->Valid()) {
109 0 : boost::this_thread::interruption_point();
110 : try {
111 0 : leveldb::Slice slKey = pcursor->key();
112 0 : CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
113 : char chType;
114 : ssKey >> chType;
115 0 : if (chType == DB_COINS) {
116 0 : leveldb::Slice slValue = pcursor->value();
117 0 : CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
118 0 : CCoins coins;
119 : ssValue >> coins;
120 : uint256 txhash;
121 : ssKey >> txhash;
122 : ss << txhash;
123 0 : ss << VARINT(coins.nVersion);
124 0 : ss << (coins.fCoinBase ? 'c' : 'n');
125 0 : ss << VARINT(coins.nHeight);
126 0 : stats.nTransactions++;
127 0 : for (unsigned int i=0; i<coins.vout.size(); i++) {
128 0 : const CTxOut &out = coins.vout[i];
129 0 : if (!out.IsNull()) {
130 0 : stats.nTransactionOutputs++;
131 0 : ss << VARINT(i+1);
132 : ss << out;
133 0 : nTotalAmount += out.nValue;
134 : }
135 : }
136 0 : stats.nSerializedSize += 32 + slValue.size();
137 0 : ss << VARINT(0);
138 : }
139 0 : pcursor->Next();
140 0 : } catch (const std::exception& e) {
141 0 : return error("%s: Deserialize or I/O error - %s", __func__, e.what());
142 : }
143 : }
144 : {
145 0 : LOCK(cs_main);
146 0 : stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
147 : }
148 0 : stats.hashSerialized = ss.GetHash();
149 0 : stats.nTotalAmount = nTotalAmount;
150 0 : return true;
151 : }
152 :
153 155 : bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
154 155 : CLevelDBBatch batch(GetObfuscateKey());
155 1287 : for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
156 128 : batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
157 : }
158 155 : batch.Write(DB_LAST_BLOCK, nLastFile);
159 22067 : for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
160 10646 : batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
161 : }
162 155 : return WriteBatch(batch, true);
163 : }
164 :
165 1 : bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
166 1 : return Read(make_pair(DB_TXINDEX, txid), pos);
167 : }
168 :
169 107 : bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
170 107 : CLevelDBBatch batch(GetObfuscateKey());
171 975 : for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
172 220 : batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
173 107 : return WriteBatch(batch);
174 : }
175 :
176 62 : bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
177 248 : return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
178 : }
179 :
180 186 : bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
181 : char ch;
182 744 : if (!Read(std::make_pair(DB_FLAG, name), ch))
183 : return false;
184 57 : fValue = ch == '1';
185 57 : return true;
186 : }
187 :
188 93 : bool CBlockTreeDB::LoadBlockIndexGuts()
189 : {
190 186 : boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
191 :
192 : CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
193 93 : ssKeySet << make_pair(DB_BLOCK_INDEX, uint256());
194 279 : pcursor->Seek(ssKeySet.str());
195 :
196 : // Load mapBlockIndex
197 11325 : while (pcursor->Valid()) {
198 11196 : boost::this_thread::interruption_point();
199 : try {
200 11196 : leveldb::Slice slKey = pcursor->key();
201 11196 : CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
202 : char chType;
203 : ssKey >> chType;
204 11196 : if (chType == DB_BLOCK_INDEX) {
205 11139 : leveldb::Slice slValue = pcursor->value();
206 11139 : CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
207 11139 : CDiskBlockIndex diskindex;
208 : ssValue >> diskindex;
209 :
210 : // Construct block index object
211 11139 : CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
212 11139 : pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
213 11139 : pindexNew->nHeight = diskindex.nHeight;
214 11139 : pindexNew->nFile = diskindex.nFile;
215 11139 : pindexNew->nDataPos = diskindex.nDataPos;
216 11139 : pindexNew->nUndoPos = diskindex.nUndoPos;
217 11139 : pindexNew->nVersion = diskindex.nVersion;
218 11139 : pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
219 11139 : pindexNew->nTime = diskindex.nTime;
220 11139 : pindexNew->nBits = diskindex.nBits;
221 11139 : pindexNew->nNonce = diskindex.nNonce;
222 11139 : pindexNew->nStatus = diskindex.nStatus;
223 11139 : pindexNew->nTx = diskindex.nTx;
224 :
225 33417 : if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
226 0 : return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
227 :
228 11139 : pcursor->Next();
229 : } else {
230 : break; // if shutdown requested or finished loading block index
231 : }
232 0 : } catch (const std::exception& e) {
233 0 : return error("%s: Deserialize or I/O error - %s", __func__, e.what());
234 : }
235 : }
236 :
237 : return true;
238 288 : }
|