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.
9 #include "chainparams.h"
13 void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
15 batch.Erase(make_pair('c', hash));
17 batch.Write(make_pair('c', hash), coins);
20 void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
21 batch.Write('B', hash);
24 CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
27 bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) {
28 return db.Read(make_pair('c', txid), coins);
31 bool CCoinsViewDB::SetCoins(const uint256 &txid, const CCoins &coins) {
33 BatchWriteCoins(batch, txid, coins);
34 return db.WriteBatch(batch);
37 bool CCoinsViewDB::HaveCoins(const uint256 &txid) {
38 return db.Exists(make_pair('c', txid));
41 CBlockIndex *CCoinsViewDB::GetBestBlock() {
42 uint256 hashBestChain;
43 if (!db.Read('B', hashBestChain))
45 std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(hashBestChain);
46 if (it == mapBlockIndex.end())
51 bool CCoinsViewDB::SetBestBlock(CBlockIndex *pindex) {
53 BatchWriteHashBestChain(batch, pindex->GetBlockHash());
54 return db.WriteBatch(batch);
57 bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
58 LogPrint("coindb", "Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());
61 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
62 BatchWriteCoins(batch, it->first, it->second);
64 BatchWriteHashBestChain(batch, pindex->GetBlockHash());
66 return db.WriteBatch(batch);
69 CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDB(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
72 bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
74 return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
77 bool CBlockTreeDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
79 return Read('I', bnBestInvalidWork);
82 bool CBlockTreeDB::WriteBestInvalidWork(const CBigNum& bnBestInvalidWork)
84 return Write('I', bnBestInvalidWork);
87 bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
88 return Write(make_pair('f', nFile), info);
91 bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
92 return Read(make_pair('f', nFile), info);
95 bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
96 return Write('l', nFile);
99 bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
101 return Write('R', '1');
106 bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
107 fReindexing = Exists('R');
111 bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
112 return Read('l', nFile);
115 bool CCoinsViewDB::GetStats(CCoinsStats &stats) {
116 leveldb::Iterator *pcursor = db.NewIterator();
117 pcursor->SeekToFirst();
119 CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
120 stats.hashBlock = GetBestBlock()->GetBlockHash();
121 ss << stats.hashBlock;
122 int64 nTotalAmount = 0;
123 while (pcursor->Valid()) {
124 boost::this_thread::interruption_point();
126 leveldb::Slice slKey = pcursor->key();
127 CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
131 leveldb::Slice slValue = pcursor->value();
132 CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
138 ss << VARINT(coins.nVersion);
139 ss << (coins.fCoinBase ? 'c' : 'n');
140 ss << VARINT(coins.nHeight);
141 stats.nTransactions++;
142 for (unsigned int i=0; i<coins.vout.size(); i++) {
143 const CTxOut &out = coins.vout[i];
145 stats.nTransactionOutputs++;
148 nTotalAmount += out.nValue;
151 stats.nSerializedSize += 32 + slValue.size();
155 } catch (std::exception &e) {
156 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
160 stats.nHeight = GetBestBlock()->nHeight;
161 stats.hashSerialized = ss.GetHash();
162 stats.nTotalAmount = nTotalAmount;
166 bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
167 return Read(make_pair('t', txid), pos);
170 bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
172 for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
173 batch.Write(make_pair('t', it->first), it->second);
174 return WriteBatch(batch);
177 bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
178 return Write(std::make_pair('F', name), fValue ? '1' : '0');
181 bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
183 if (!Read(std::make_pair('F', name), ch))
189 bool CBlockTreeDB::LoadBlockIndexGuts()
191 leveldb::Iterator *pcursor = NewIterator();
193 CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
194 ssKeySet << make_pair('b', uint256(0));
195 pcursor->Seek(ssKeySet.str());
197 // Load mapBlockIndex
198 while (pcursor->Valid()) {
199 boost::this_thread::interruption_point();
201 leveldb::Slice slKey = pcursor->key();
202 CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
206 leveldb::Slice slValue = pcursor->value();
207 CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
208 CDiskBlockIndex diskindex;
209 ssValue >> diskindex;
211 // Construct block index object
212 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
213 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
214 pindexNew->nHeight = diskindex.nHeight;
215 pindexNew->nFile = diskindex.nFile;
216 pindexNew->nDataPos = diskindex.nDataPos;
217 pindexNew->nUndoPos = diskindex.nUndoPos;
218 pindexNew->nVersion = diskindex.nVersion;
219 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
220 pindexNew->nTime = diskindex.nTime;
221 pindexNew->nBits = diskindex.nBits;
222 pindexNew->nNonce = diskindex.nNonce;
223 pindexNew->nStatus = diskindex.nStatus;
224 pindexNew->nTx = diskindex.nTx;
226 // Watch for genesis block
227 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == Params().HashGenesisBlock())
228 pindexGenesisBlock = pindexNew;
230 if (!pindexNew->CheckIndex())
231 return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString().c_str());
235 break; // if shutdown requested or finished loading block index
237 } catch (std::exception &e) {
238 return error("%s() : deserialize error", __PRETTY_FUNCTION__);