Bitcoin v0.2.0 · 2009-12-16
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"67void ThreadFlushWalletDB(void* parg);8910unsigned int nWalletDBUpdated;1112131415//16// CDB17//1819static CCriticalSection cs_db;20static bool fDbEnvInit = false;21DbEnv dbenv(0);22static map<string, int> mapFileUseCount;23static map<string, Db*> mapDb;2425class CDBInit26{27public:28 CDBInit()29 {30 }31 ~CDBInit()32 {33 if (fDbEnvInit)34 {35 dbenv.close(0);36 fDbEnvInit = false;37 }38 }39}40instance_of_cdbinit;414243CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)44{45 int ret;46 if (pszFile == NULL)47 return;4849 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));50 bool fCreate = strchr(pszMode, 'c');51 unsigned int nFlags = DB_THREAD;52 if (fCreate)53 nFlags |= DB_CREATE;5455 CRITICAL_BLOCK(cs_db)56 {57 if (!fDbEnvInit)58 {59 if (fShutdown)60 return;61 string strDataDir = GetDataDir();62 string strLogDir = strDataDir + "/database";63 _mkdir(strLogDir.c_str());64 string strErrorFile = strDataDir + "/db.log";65 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());6667 dbenv.set_lg_dir(strLogDir.c_str());68 dbenv.set_lg_max(10000000);69 dbenv.set_lk_max_locks(10000);70 dbenv.set_lk_max_objects(10000);71 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug72 dbenv.set_flags(DB_AUTO_COMMIT, 1);73 ret = dbenv.open(strDataDir.c_str(),74 DB_CREATE |75 DB_INIT_LOCK |76 DB_INIT_LOG |77 DB_INIT_MPOOL |78 DB_INIT_TXN |79 DB_THREAD |80 DB_PRIVATE |81 DB_RECOVER,82 S_IRUSR | S_IWUSR);83 if (ret > 0)84 throw runtime_error(strprintf("CDB() : error %d opening database environment\n", ret));85 fDbEnvInit = true;86 }8788 strFile = pszFile;89 ++mapFileUseCount[strFile];90 pdb = mapDb[strFile];91 if (pdb == NULL)92 {93 pdb = new Db(&dbenv, 0);9495 ret = pdb->open(NULL, // Txn pointer96 pszFile, // Filename97 "main", // Logical db name98 DB_BTREE, // Database type99 nFlags, // Flags100 0);101102 if (ret > 0)103 {104 delete pdb;105 pdb = NULL;106 CRITICAL_BLOCK(cs_db)107 --mapFileUseCount[strFile];108 strFile = "";109 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d\n", pszFile, ret));110 }111112 if (fCreate && !Exists(string("version")))113 {114 bool fTmp = fReadOnly;115 fReadOnly = false;116 WriteVersion(VERSION);117 fReadOnly = fTmp;118 }119120 mapDb[strFile] = pdb;121 }122 }123}124125void CDB::Close()126{127 if (!pdb)128 return;129 if (!vTxn.empty())130 vTxn.front()->abort();131 vTxn.clear();132 pdb = NULL;133 dbenv.txn_checkpoint(0, 0, 0);134135 CRITICAL_BLOCK(cs_db)136 --mapFileUseCount[strFile];137138 RandAddSeed();139}140141void CloseDb(const string& strFile)142{143 CRITICAL_BLOCK(cs_db)144 {145 if (mapDb[strFile] != NULL)146 {147 // Close the database handle148 Db* pdb = mapDb[strFile];149 pdb->close(0);150 delete pdb;151 mapDb[strFile] = NULL;152 }153 }154}155156void DBFlush(bool fShutdown)157{158 // Flush log data to the actual data file159 // on all files that are not in use160 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");161 if (!fDbEnvInit)162 return;163 CRITICAL_BLOCK(cs_db)164 {165 map<string, int>::iterator mi = mapFileUseCount.begin();166 while (mi != mapFileUseCount.end())167 {168 string strFile = (*mi).first;169 int nRefCount = (*mi).second;170 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);171 if (nRefCount == 0)172 {173 // Move log data to the dat file174 CloseDb(strFile);175 dbenv.txn_checkpoint(0, 0, 0);176 printf("%s flush\n", strFile.c_str());177 dbenv.lsn_reset(strFile.c_str(), 0);178 mapFileUseCount.erase(mi++);179 }180 else181 mi++;182 }183 if (fShutdown)184 {185 char** listp;186 if (mapFileUseCount.empty())187 dbenv.log_archive(&listp, DB_ARCH_REMOVE);188 dbenv.close(0);189 fDbEnvInit = false;190 }191 }192}193194195196197198199//200// CTxDB201//202203bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)204{205 assert(!fClient);206 txindex.SetNull();207 return Read(make_pair(string("tx"), hash), txindex);208}209210bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)211{212 assert(!fClient);213 return Write(make_pair(string("tx"), hash), txindex);214}215216bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)217{218 assert(!fClient);219220 // Add to tx index221 uint256 hash = tx.GetHash();222 CTxIndex txindex(pos, tx.vout.size());223 return Write(make_pair(string("tx"), hash), txindex);224}225226bool CTxDB::EraseTxIndex(const CTransaction& tx)227{228 assert(!fClient);229 uint256 hash = tx.GetHash();230231 return Erase(make_pair(string("tx"), hash));232}233234bool CTxDB::ContainsTx(uint256 hash)235{236 assert(!fClient);237 return Exists(make_pair(string("tx"), hash));238}239240bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)241{242 assert(!fClient);243 vtx.clear();244245 // Get cursor246 Dbc* pcursor = GetCursor();247 if (!pcursor)248 return false;249250 unsigned int fFlags = DB_SET_RANGE;251 loop252 {253 // Read next record254 CDataStream ssKey;255 if (fFlags == DB_SET_RANGE)256 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);257 CDataStream ssValue;258 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);259 fFlags = DB_NEXT;260 if (ret == DB_NOTFOUND)261 break;262 else if (ret != 0)263 {264 pcursor->close();265 return false;266 }267268 // Unserialize269 string strType;270 uint160 hashItem;271 CDiskTxPos pos;272 ssKey >> strType >> hashItem >> pos;273 int nItemHeight;274 ssValue >> nItemHeight;275276 // Read transaction277 if (strType != "owner" || hashItem != hash160)278 break;279 if (nItemHeight >= nMinHeight)280 {281 vtx.resize(vtx.size()+1);282 if (!vtx.back().ReadFromDisk(pos))283 {284 pcursor->close();285 return false;286 }287 }288 }289290 pcursor->close();291 return true;292}293294bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)295{296 assert(!fClient);297 tx.SetNull();298 if (!ReadTxIndex(hash, txindex))299 return false;300 return (tx.ReadFromDisk(txindex.pos));301}302303bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)304{305 CTxIndex txindex;306 return ReadDiskTx(hash, tx, txindex);307}308309bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)310{311 return ReadDiskTx(outpoint.hash, tx, txindex);312}313314bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)315{316 CTxIndex txindex;317 return ReadDiskTx(outpoint.hash, tx, txindex);318}319320bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)321{322 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);323}324325bool CTxDB::EraseBlockIndex(uint256 hash)326{327 return Erase(make_pair(string("blockindex"), hash));328}329330bool CTxDB::ReadHashBestChain(uint256& hashBestChain)331{332 return Read(string("hashBestChain"), hashBestChain);333}334335bool CTxDB::WriteHashBestChain(uint256 hashBestChain)336{337 return Write(string("hashBestChain"), hashBestChain);338}339340CBlockIndex* InsertBlockIndex(uint256 hash)341{342 if (hash == 0)343 return NULL;344345 // Return existing346 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);347 if (mi != mapBlockIndex.end())348 return (*mi).second;349350 // Create new351 CBlockIndex* pindexNew = new CBlockIndex();352 if (!pindexNew)353 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");354 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;355 pindexNew->phashBlock = &((*mi).first);356357 return pindexNew;358}359360bool CTxDB::LoadBlockIndex()361{362 // Get cursor363 Dbc* pcursor = GetCursor();364 if (!pcursor)365 return false;366367 unsigned int fFlags = DB_SET_RANGE;368 loop369 {370 // Read next record371 CDataStream ssKey;372 if (fFlags == DB_SET_RANGE)373 ssKey << make_pair(string("blockindex"), uint256(0));374 CDataStream ssValue;375 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);376 fFlags = DB_NEXT;377 if (ret == DB_NOTFOUND)378 break;379 else if (ret != 0)380 return false;381382 // Unserialize383 string strType;384 ssKey >> strType;385 if (strType == "blockindex")386 {387 CDiskBlockIndex diskindex;388 ssValue >> diskindex;389390 // Construct block index object391 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());392 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);393 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);394 pindexNew->nFile = diskindex.nFile;395 pindexNew->nBlockPos = diskindex.nBlockPos;396 pindexNew->nHeight = diskindex.nHeight;397 pindexNew->nVersion = diskindex.nVersion;398 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;399 pindexNew->nTime = diskindex.nTime;400 pindexNew->nBits = diskindex.nBits;401 pindexNew->nNonce = diskindex.nNonce;402403 // Watch for genesis block and best block404 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)405 pindexGenesisBlock = pindexNew;406 }407 else408 {409 break;410 }411 }412 pcursor->close();413414 if (!ReadHashBestChain(hashBestChain))415 {416 if (pindexGenesisBlock == NULL)417 return true;418 return error("CTxDB::LoadBlockIndex() : hashBestChain not found");419 }420421 if (!mapBlockIndex.count(hashBestChain))422 return error("CTxDB::LoadBlockIndex() : blockindex for hashBestChain not found");423 pindexBest = mapBlockIndex[hashBestChain];424 nBestHeight = pindexBest->nHeight;425 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);426427 return true;428}429430431432433434//435// CAddrDB436//437438bool CAddrDB::WriteAddress(const CAddress& addr)439{440 return Write(make_pair(string("addr"), addr.GetKey()), addr);441}442443bool CAddrDB::LoadAddresses()444{445 CRITICAL_BLOCK(cs_mapAddresses)446 {447 // Load user provided addresses448 CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");449 if (filein)450 {451 try452 {453 char psz[1000];454 while (fgets(psz, sizeof(psz), filein))455 {456 CAddress addr(psz, NODE_NETWORK);457 addr.nTime = 0; // so it won't relay unless successfully connected458 if (addr.IsValid())459 AddAddress(*this, addr);460 }461 }462 catch (...) { }463 }464465 // Get cursor466 Dbc* pcursor = GetCursor();467 if (!pcursor)468 return false;469470 loop471 {472 // Read next record473 CDataStream ssKey;474 CDataStream ssValue;475 int ret = ReadAtCursor(pcursor, ssKey, ssValue);476 if (ret == DB_NOTFOUND)477 break;478 else if (ret != 0)479 return false;480481 // Unserialize482 string strType;483 ssKey >> strType;484 if (strType == "addr")485 {486 CAddress addr;487 ssValue >> addr;488 mapAddresses.insert(make_pair(addr.GetKey(), addr));489 }490 }491 pcursor->close();492493 printf("Loaded %d addresses\n", mapAddresses.size());494495 // Fix for possible bug that manifests in mapAddresses.count in irc.cpp,496 // just need to call count here and it doesn't happen there. The bug was the497 // pack pragma in irc.cpp and has been fixed, but I'm not in a hurry to delete this.498 mapAddresses.count(vector<unsigned char>(18));499 }500501 return true;502}503504bool LoadAddresses()505{506 return CAddrDB("cr+").LoadAddresses();507}508509510511512//513// CReviewDB514//515516bool CReviewDB::ReadReviews(uint256 hash, vector<CReview>& vReviews)517{518 vReviews.size(); // msvc workaround, just need to do anything with vReviews519 return Read(make_pair(string("reviews"), hash), vReviews);520}521522bool CReviewDB::WriteReviews(uint256 hash, const vector<CReview>& vReviews)523{524 return Write(make_pair(string("reviews"), hash), vReviews);525}526527528529530531532533//534// CWalletDB535//536537bool CWalletDB::LoadWallet(vector<unsigned char>& vchDefaultKeyRet)538{539 vchDefaultKeyRet.clear();540 int nFileVersion = 0;541542 // Modify defaults543#ifndef __WXMSW__544 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program545 fMinimizeToTray = false;546 fMinimizeOnClose = false;547#endif548549 //// todo: shouldn't we catch exceptions and try to recover and continue?550 CRITICAL_BLOCK(cs_mapKeys)551 CRITICAL_BLOCK(cs_mapWallet)552 {553 // Get cursor554 Dbc* pcursor = GetCursor();555 if (!pcursor)556 return false;557558 loop559 {560 // Read next record561 CDataStream ssKey;562 CDataStream ssValue;563 int ret = ReadAtCursor(pcursor, ssKey, ssValue);564 if (ret == DB_NOTFOUND)565 break;566 else if (ret != 0)567 return false;568569 // Unserialize570 // Taking advantage of the fact that pair serialization571 // is just the two items serialized one after the other572 string strType;573 ssKey >> strType;574 if (strType == "name")575 {576 string strAddress;577 ssKey >> strAddress;578 ssValue >> mapAddressBook[strAddress];579 }580 else if (strType == "tx")581 {582 uint256 hash;583 ssKey >> hash;584 CWalletTx& wtx = mapWallet[hash];585 ssValue >> wtx;586587 if (wtx.GetHash() != hash)588 printf("Error in wallet.dat, hash mismatch\n");589590 //// debug print591 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());592 //printf(" %12I64d %s %s %s\n",593 // wtx.vout[0].nValue,594 // DateTimeStrFormat("%x %H:%M:%S", wtx.nTime).c_str(),595 // wtx.hashBlock.ToString().substr(0,16).c_str(),596 // wtx.mapValue["message"].c_str());597 }598 else if (strType == "key")599 {600 vector<unsigned char> vchPubKey;601 ssKey >> vchPubKey;602 CPrivKey vchPrivKey;603 ssValue >> vchPrivKey;604605 mapKeys[vchPubKey] = vchPrivKey;606 mapPubKeys[Hash160(vchPubKey)] = vchPubKey;607 }608 else if (strType == "defaultkey")609 {610 ssValue >> vchDefaultKeyRet;611 }612 else if (strType == "version")613 {614 ssValue >> nFileVersion;615 }616 else if (strType == "setting")617 {618 string strKey;619 ssKey >> strKey;620621 // Menu state622 if (strKey == "fShowGenerated") ssValue >> fShowGenerated;623 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;624625 // Options626 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;627 if (strKey == "addrIncoming") ssValue >> addrIncoming;628 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;629 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;630 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;631 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;632 if (strKey == "fUseProxy") ssValue >> fUseProxy;633 if (strKey == "addrProxy") ssValue >> addrProxy;634635 }636 }637 pcursor->close();638 }639640 printf("nFileVersion = %d\n", nFileVersion);641 printf("fShowGenerated = %d\n", fShowGenerated);642 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);643 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);644 printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());645 printf("fMinimizeToTray = %d\n", fMinimizeToTray);646 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);647 printf("fUseProxy = %d\n", fUseProxy);648 printf("addrProxy = %s\n", addrProxy.ToString().c_str());649650651 // The transaction fee setting won't be needed for many years to come.652 // Setting it to zero here in case they set it to something in an earlier version.653 if (nTransactionFee != 0)654 {655 nTransactionFee = 0;656 WriteSetting("nTransactionFee", nTransactionFee);657 }658659 // Upgrade660 if (nFileVersion < VERSION)661 {662 // Get rid of old debug.log file in current directory663 if (nFileVersion <= 105 && !pszSetDataDir[0])664 unlink("debug.log");665666 WriteVersion(VERSION);667 }668669 return true;670}671672bool LoadWallet(bool& fFirstRunRet)673{674 fFirstRunRet = false;675 vector<unsigned char> vchDefaultKey;676 if (!CWalletDB("cr+").LoadWallet(vchDefaultKey))677 return false;678 fFirstRunRet = vchDefaultKey.empty();679680 if (mapKeys.count(vchDefaultKey))681 {682 // Set keyUser683 keyUser.SetPubKey(vchDefaultKey);684 keyUser.SetPrivKey(mapKeys[vchDefaultKey]);685 }686 else687 {688 // Create new keyUser and set as default key689 RandAddSeedPerfmon();690 keyUser.MakeNewKey();691 if (!AddKey(keyUser))692 return false;693 if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))694 return false;695 CWalletDB().WriteDefaultKey(keyUser.GetPubKey());696 }697698 CreateThread(ThreadFlushWalletDB, NULL);699 return true;700}701702void ThreadFlushWalletDB(void* parg)703{704 static bool fOneThread;705 if (fOneThread)706 return;707 fOneThread = true;708 if (mapArgs.count("-noflushwallet"))709 return;710711 unsigned int nLastSeen = nWalletDBUpdated;712 unsigned int nLastFlushed = nWalletDBUpdated;713 int64 nLastWalletUpdate = GetTime();714 while (!fShutdown)715 {716 Sleep(500);717718 if (nLastSeen != nWalletDBUpdated)719 {720 nLastSeen = nWalletDBUpdated;721 nLastWalletUpdate = GetTime();722 }723724 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)725 {726 TRY_CRITICAL_BLOCK(cs_db)727 {728 // Don't do this if any databases are in use729 int nRefCount = 0;730 map<string, int>::iterator mi = mapFileUseCount.begin();731 while (mi != mapFileUseCount.end())732 {733 nRefCount += (*mi).second;734 mi++;735 }736737 if (nRefCount == 0 && !fShutdown)738 {739 string strFile = "wallet.dat";740 map<string, int>::iterator mi = mapFileUseCount.find(strFile);741 if (mi != mapFileUseCount.end())742 {743 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());744 printf("Flushing wallet.dat\n");745 nLastFlushed = nWalletDBUpdated;746 int64 nStart = GetTimeMillis();747748 // Flush wallet.dat so it's self contained749 CloseDb(strFile);750 dbenv.txn_checkpoint(0, 0, 0);751 dbenv.lsn_reset(strFile.c_str(), 0);752753 mapFileUseCount.erase(mi++);754 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);755 }756 }757 }758 }759 }760}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
