Bitcoin v0.1.5 · 2009-02-04
db.cpp
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"6789101112//13// CDB14//1516static CCriticalSection cs_db;17static bool fDbEnvInit = false;18DbEnv dbenv(0);19static map<string, int> mapFileUseCount;2021class CDBInit22{23public:24 CDBInit()25 {26 }27 ~CDBInit()28 {29 if (fDbEnvInit)30 {31 dbenv.close(0);32 fDbEnvInit = false;33 }34 }35}36instance_of_cdbinit;373839CDB::CDB(const char* pszFile, const char* pszMode, bool fTxn) : pdb(NULL)40{41 int ret;42 if (pszFile == NULL)43 return;4445 bool fCreate = strchr(pszMode, 'c');46 bool fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));47 unsigned int nFlags = DB_THREAD;48 if (fCreate)49 nFlags |= DB_CREATE;50 else if (fReadOnly)51 nFlags |= DB_RDONLY;52 if (!fReadOnly || fTxn)53 nFlags |= DB_AUTO_COMMIT;5455 CRITICAL_BLOCK(cs_db)56 {57 if (!fDbEnvInit)58 {59 string strAppDir = GetAppDir();60 string strLogDir = strAppDir + "\\database";61 _mkdir(strLogDir.c_str());62 printf("dbenv.open strAppDir=%s\n", strAppDir.c_str());6364 dbenv.set_lg_dir(strLogDir.c_str());65 dbenv.set_lg_max(10000000);66 dbenv.set_lk_max_locks(10000);67 dbenv.set_lk_max_objects(10000);68 dbenv.set_errfile(fopen("db.log", "a")); /// debug69 ///dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1); /// causes corruption70 ret = dbenv.open(strAppDir.c_str(),71 DB_CREATE |72 DB_INIT_LOCK |73 DB_INIT_LOG |74 DB_INIT_MPOOL |75 DB_INIT_TXN |76 DB_THREAD |77 DB_PRIVATE |78 DB_RECOVER,79 0);80 if (ret > 0)81 throw runtime_error(strprintf("CDB() : error %d opening database environment\n", ret));82 fDbEnvInit = true;83 }8485 strFile = pszFile;86 ++mapFileUseCount[strFile];87 }8889 pdb = new Db(&dbenv, 0);9091 ret = pdb->open(NULL, // Txn pointer92 pszFile, // Filename93 "main", // Logical db name94 DB_BTREE, // Database type95 nFlags, // Flags96 0);9798 if (ret > 0)99 {100 delete pdb;101 pdb = NULL;102 CRITICAL_BLOCK(cs_db)103 --mapFileUseCount[strFile];104 strFile = "";105 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d\n", pszFile, ret));106 }107108 if (fCreate && !Exists(string("version")))109 WriteVersion(VERSION);110111 RandAddSeed();112}113114void CDB::Close()115{116 if (!pdb)117 return;118 if (!vTxn.empty())119 vTxn.front()->abort();120 vTxn.clear();121 pdb->close(0);122 delete pdb;123 pdb = NULL;124 dbenv.txn_checkpoint(0, 0, 0);125126 CRITICAL_BLOCK(cs_db)127 --mapFileUseCount[strFile];128129 RandAddSeed();130}131132void DBFlush(bool fShutdown)133{134 // Flush log data to the actual data file135 // on all files that are not in use136 printf("DBFlush(%s)\n", fShutdown ? "true" : "false");137 CRITICAL_BLOCK(cs_db)138 {139 dbenv.txn_checkpoint(0, 0, 0);140 map<string, int>::iterator mi = mapFileUseCount.begin();141 while (mi != mapFileUseCount.end())142 {143 string strFile = (*mi).first;144 int nRefCount = (*mi).second;145 if (nRefCount == 0)146 {147 dbenv.lsn_reset(strFile.c_str(), 0);148 mapFileUseCount.erase(mi++);149 }150 else151 mi++;152 }153 if (fShutdown)154 {155 char** listp;156 if (mapFileUseCount.empty())157 dbenv.log_archive(&listp, DB_ARCH_REMOVE);158 dbenv.close(0);159 fDbEnvInit = false;160 }161 }162}163164165166167168169//170// CTxDB171//172173bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)174{175 assert(!fClient);176 txindex.SetNull();177 return Read(make_pair(string("tx"), hash), txindex);178}179180bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)181{182 assert(!fClient);183 return Write(make_pair(string("tx"), hash), txindex);184}185186bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)187{188 assert(!fClient);189190 // Add to tx index191 uint256 hash = tx.GetHash();192 CTxIndex txindex(pos, tx.vout.size());193 return Write(make_pair(string("tx"), hash), txindex);194}195196bool CTxDB::EraseTxIndex(const CTransaction& tx)197{198 assert(!fClient);199 uint256 hash = tx.GetHash();200201 return Erase(make_pair(string("tx"), hash));202}203204bool CTxDB::ContainsTx(uint256 hash)205{206 assert(!fClient);207 return Exists(make_pair(string("tx"), hash));208}209210bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)211{212 assert(!fClient);213 vtx.clear();214215 // Get cursor216 Dbc* pcursor = GetCursor();217 if (!pcursor)218 return false;219220 unsigned int fFlags = DB_SET_RANGE;221 loop222 {223 // Read next record224 CDataStream ssKey;225 if (fFlags == DB_SET_RANGE)226 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);227 CDataStream ssValue;228 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);229 fFlags = DB_NEXT;230 if (ret == DB_NOTFOUND)231 break;232 else if (ret != 0)233 return false;234235 // Unserialize236 string strType;237 uint160 hashItem;238 CDiskTxPos pos;239 ssKey >> strType >> hashItem >> pos;240 int nItemHeight;241 ssValue >> nItemHeight;242243 // Read transaction244 if (strType != "owner" || hashItem != hash160)245 break;246 if (nItemHeight >= nMinHeight)247 {248 vtx.resize(vtx.size()+1);249 if (!vtx.back().ReadFromDisk(pos))250 return false;251 }252 }253 return true;254}255256bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)257{258 assert(!fClient);259 tx.SetNull();260 if (!ReadTxIndex(hash, txindex))261 return false;262 return (tx.ReadFromDisk(txindex.pos));263}264265bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)266{267 CTxIndex txindex;268 return ReadDiskTx(hash, tx, txindex);269}270271bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)272{273 return ReadDiskTx(outpoint.hash, tx, txindex);274}275276bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)277{278 CTxIndex txindex;279 return ReadDiskTx(outpoint.hash, tx, txindex);280}281282bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)283{284 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);285}286287bool CTxDB::EraseBlockIndex(uint256 hash)288{289 return Erase(make_pair(string("blockindex"), hash));290}291292bool CTxDB::ReadHashBestChain(uint256& hashBestChain)293{294 return Read(string("hashBestChain"), hashBestChain);295}296297bool CTxDB::WriteHashBestChain(uint256 hashBestChain)298{299 return Write(string("hashBestChain"), hashBestChain);300}301302CBlockIndex* InsertBlockIndex(uint256 hash)303{304 if (hash == 0)305 return NULL;306307 // Return existing308 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);309 if (mi != mapBlockIndex.end())310 return (*mi).second;311312 // Create new313 CBlockIndex* pindexNew = new CBlockIndex();314 if (!pindexNew)315 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");316 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;317 pindexNew->phashBlock = &((*mi).first);318319 return pindexNew;320}321322bool CTxDB::LoadBlockIndex()323{324 // Get cursor325 Dbc* pcursor = GetCursor();326 if (!pcursor)327 return false;328329 unsigned int fFlags = DB_SET_RANGE;330 loop331 {332 // Read next record333 CDataStream ssKey;334 if (fFlags == DB_SET_RANGE)335 ssKey << make_pair(string("blockindex"), uint256(0));336 CDataStream ssValue;337 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);338 fFlags = DB_NEXT;339 if (ret == DB_NOTFOUND)340 break;341 else if (ret != 0)342 return false;343344 // Unserialize345 string strType;346 ssKey >> strType;347 if (strType == "blockindex")348 {349 CDiskBlockIndex diskindex;350 ssValue >> diskindex;351352 // Construct block index object353 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());354 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);355 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);356 pindexNew->nFile = diskindex.nFile;357 pindexNew->nBlockPos = diskindex.nBlockPos;358 pindexNew->nHeight = diskindex.nHeight;359 pindexNew->nVersion = diskindex.nVersion;360 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;361 pindexNew->nTime = diskindex.nTime;362 pindexNew->nBits = diskindex.nBits;363 pindexNew->nNonce = diskindex.nNonce;364365 // Watch for genesis block and best block366 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)367 pindexGenesisBlock = pindexNew;368 }369 else370 {371 break;372 }373 }374375 if (!ReadHashBestChain(hashBestChain))376 {377 if (pindexGenesisBlock == NULL)378 return true;379 return error("CTxDB::LoadBlockIndex() : hashBestChain not found\n");380 }381382 if (!mapBlockIndex.count(hashBestChain))383 return error("CTxDB::LoadBlockIndex() : blockindex for hashBestChain not found\n");384 pindexBest = mapBlockIndex[hashBestChain];385 nBestHeight = pindexBest->nHeight;386 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,14).c_str(), nBestHeight);387388 return true;389}390391392393394395//396// CAddrDB397//398399bool CAddrDB::WriteAddress(const CAddress& addr)400{401 return Write(make_pair(string("addr"), addr.GetKey()), addr);402}403404bool CAddrDB::LoadAddresses()405{406 CRITICAL_BLOCK(cs_mapIRCAddresses)407 CRITICAL_BLOCK(cs_mapAddresses)408 {409 // Load user provided addresses410 CAutoFile filein = fopen("addr.txt", "rt");411 if (filein)412 {413 try414 {415 char psz[1000];416 while (fgets(psz, sizeof(psz), filein))417 {418 CAddress addr(psz, NODE_NETWORK);419 if (addr.ip != 0)420 {421 AddAddress(*this, addr);422 mapIRCAddresses.insert(make_pair(addr.GetKey(), addr));423 }424 }425 }426 catch (...) { }427 }428429 // Get cursor430 Dbc* pcursor = GetCursor();431 if (!pcursor)432 return false;433434 loop435 {436 // Read next record437 CDataStream ssKey;438 CDataStream ssValue;439 int ret = ReadAtCursor(pcursor, ssKey, ssValue);440 if (ret == DB_NOTFOUND)441 break;442 else if (ret != 0)443 return false;444445 // Unserialize446 string strType;447 ssKey >> strType;448 if (strType == "addr")449 {450 CAddress addr;451 ssValue >> addr;452 mapAddresses.insert(make_pair(addr.GetKey(), addr));453 }454 }455456 //// debug print457 printf("mapAddresses:\n");458 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)459 item.second.print();460 printf("-----\n");461462 // Fix for possible bug that manifests in mapAddresses.count in irc.cpp,463 // just need to call count here and it doesn't happen there. The bug was the464 // pack pragma in irc.cpp and has been fixed, but I'm not in a hurry to delete this.465 mapAddresses.count(vector<unsigned char>(18));466 }467468 return true;469}470471bool LoadAddresses()472{473 return CAddrDB("cr+").LoadAddresses();474}475476477478479//480// CReviewDB481//482483bool CReviewDB::ReadReviews(uint256 hash, vector<CReview>& vReviews)484{485 vReviews.size(); // msvc workaround, just need to do anything with vReviews486 return Read(make_pair(string("reviews"), hash), vReviews);487}488489bool CReviewDB::WriteReviews(uint256 hash, const vector<CReview>& vReviews)490{491 return Write(make_pair(string("reviews"), hash), vReviews);492}493494495496497498499500//501// CWalletDB502//503504bool CWalletDB::LoadWallet(vector<unsigned char>& vchDefaultKeyRet)505{506 vchDefaultKeyRet.clear();507508 //// todo: shouldn't we catch exceptions and try to recover and continue?509 CRITICAL_BLOCK(cs_mapKeys)510 CRITICAL_BLOCK(cs_mapWallet)511 {512 // Get cursor513 Dbc* pcursor = GetCursor();514 if (!pcursor)515 return false;516517 loop518 {519 // Read next record520 CDataStream ssKey;521 CDataStream ssValue;522 int ret = ReadAtCursor(pcursor, ssKey, ssValue);523 if (ret == DB_NOTFOUND)524 break;525 else if (ret != 0)526 return false;527528 // Unserialize529 // Taking advantage of the fact that pair serialization530 // is just the two items serialized one after the other531 string strType;532 ssKey >> strType;533 if (strType == "name")534 {535 string strAddress;536 ssKey >> strAddress;537 ssValue >> mapAddressBook[strAddress];538 }539 else if (strType == "tx")540 {541 uint256 hash;542 ssKey >> hash;543 CWalletTx& wtx = mapWallet[hash];544 ssValue >> wtx;545546 if (wtx.GetHash() != hash)547 printf("Error in wallet.dat, hash mismatch\n");548549 //// debug print550 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());551 //printf(" %12I64d %s %s %s\n",552 // wtx.vout[0].nValue,553 // DateTimeStr(wtx.nTime).c_str(),554 // wtx.hashBlock.ToString().substr(0,14).c_str(),555 // wtx.mapValue["message"].c_str());556 }557 else if (strType == "key")558 {559 vector<unsigned char> vchPubKey;560 ssKey >> vchPubKey;561 CPrivKey vchPrivKey;562 ssValue >> vchPrivKey;563564 mapKeys[vchPubKey] = vchPrivKey;565 mapPubKeys[Hash160(vchPubKey)] = vchPubKey;566 }567 else if (strType == "defaultkey")568 {569 ssValue >> vchDefaultKeyRet;570 }571 else if (strType == "setting") /// or settings or option or options or config?572 {573 string strKey;574 ssKey >> strKey;575 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;576 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;577 if (strKey == "addrIncoming") ssValue >> addrIncoming;578 }579 }580 }581582 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);583 printf("nTransactionFee = %I64d\n", nTransactionFee);584 printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());585586 return true;587}588589bool LoadWallet()590{591 vector<unsigned char> vchDefaultKey;592 if (!CWalletDB("cr").LoadWallet(vchDefaultKey))593 return false;594595 if (mapKeys.count(vchDefaultKey))596 {597 // Set keyUser598 keyUser.SetPubKey(vchDefaultKey);599 keyUser.SetPrivKey(mapKeys[vchDefaultKey]);600 }601 else602 {603 // Create new keyUser and set as default key604 RandAddSeed(true);605 keyUser.MakeNewKey();606 if (!AddKey(keyUser))607 return false;608 if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))609 return false;610 CWalletDB().WriteDefaultKey(keyUser.GetPubKey());611 }612613 return true;614}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
