Bitcoin v0.3.10 · 2010-08-15
db.cpp
1// Copyright (c) 2009-2010 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 filesystem::create_directory(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;133134 // Flush database activity from memory pool to disk log135 unsigned int nMinutes = 0;136 if (strFile == "addr.dat")137 nMinutes = 2;138 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)139 nMinutes = 1;140 dbenv.txn_checkpoint(0, nMinutes, 0);141142 CRITICAL_BLOCK(cs_db)143 --mapFileUseCount[strFile];144}145146void CloseDb(const string& strFile)147{148 CRITICAL_BLOCK(cs_db)149 {150 if (mapDb[strFile] != NULL)151 {152 // Close the database handle153 Db* pdb = mapDb[strFile];154 pdb->close(0);155 delete pdb;156 mapDb[strFile] = NULL;157 }158 }159}160161void DBFlush(bool fShutdown)162{163 // Flush log data to the actual data file164 // on all files that are not in use165 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");166 if (!fDbEnvInit)167 return;168 CRITICAL_BLOCK(cs_db)169 {170 map<string, int>::iterator mi = mapFileUseCount.begin();171 while (mi != mapFileUseCount.end())172 {173 string strFile = (*mi).first;174 int nRefCount = (*mi).second;175 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);176 if (nRefCount == 0)177 {178 // Move log data to the dat file179 CloseDb(strFile);180 dbenv.txn_checkpoint(0, 0, 0);181 printf("%s flush\n", strFile.c_str());182 dbenv.lsn_reset(strFile.c_str(), 0);183 mapFileUseCount.erase(mi++);184 }185 else186 mi++;187 }188 if (fShutdown)189 {190 char** listp;191 if (mapFileUseCount.empty())192 dbenv.log_archive(&listp, DB_ARCH_REMOVE);193 dbenv.close(0);194 fDbEnvInit = false;195 }196 }197}198199200201202203204//205// CTxDB206//207208bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)209{210 assert(!fClient);211 txindex.SetNull();212 return Read(make_pair(string("tx"), hash), txindex);213}214215bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)216{217 assert(!fClient);218 return Write(make_pair(string("tx"), hash), txindex);219}220221bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)222{223 assert(!fClient);224225 // Add to tx index226 uint256 hash = tx.GetHash();227 CTxIndex txindex(pos, tx.vout.size());228 return Write(make_pair(string("tx"), hash), txindex);229}230231bool CTxDB::EraseTxIndex(const CTransaction& tx)232{233 assert(!fClient);234 uint256 hash = tx.GetHash();235236 return Erase(make_pair(string("tx"), hash));237}238239bool CTxDB::ContainsTx(uint256 hash)240{241 assert(!fClient);242 return Exists(make_pair(string("tx"), hash));243}244245bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)246{247 assert(!fClient);248 vtx.clear();249250 // Get cursor251 Dbc* pcursor = GetCursor();252 if (!pcursor)253 return false;254255 unsigned int fFlags = DB_SET_RANGE;256 loop257 {258 // Read next record259 CDataStream ssKey;260 if (fFlags == DB_SET_RANGE)261 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);262 CDataStream ssValue;263 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);264 fFlags = DB_NEXT;265 if (ret == DB_NOTFOUND)266 break;267 else if (ret != 0)268 {269 pcursor->close();270 return false;271 }272273 // Unserialize274 string strType;275 uint160 hashItem;276 CDiskTxPos pos;277 ssKey >> strType >> hashItem >> pos;278 int nItemHeight;279 ssValue >> nItemHeight;280281 // Read transaction282 if (strType != "owner" || hashItem != hash160)283 break;284 if (nItemHeight >= nMinHeight)285 {286 vtx.resize(vtx.size()+1);287 if (!vtx.back().ReadFromDisk(pos))288 {289 pcursor->close();290 return false;291 }292 }293 }294295 pcursor->close();296 return true;297}298299bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)300{301 assert(!fClient);302 tx.SetNull();303 if (!ReadTxIndex(hash, txindex))304 return false;305 return (tx.ReadFromDisk(txindex.pos));306}307308bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)309{310 CTxIndex txindex;311 return ReadDiskTx(hash, tx, txindex);312}313314bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)315{316 return ReadDiskTx(outpoint.hash, tx, txindex);317}318319bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)320{321 CTxIndex txindex;322 return ReadDiskTx(outpoint.hash, tx, txindex);323}324325bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)326{327 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);328}329330bool CTxDB::EraseBlockIndex(uint256 hash)331{332 return Erase(make_pair(string("blockindex"), hash));333}334335bool CTxDB::ReadHashBestChain(uint256& hashBestChain)336{337 return Read(string("hashBestChain"), hashBestChain);338}339340bool CTxDB::WriteHashBestChain(uint256 hashBestChain)341{342 return Write(string("hashBestChain"), hashBestChain);343}344345bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)346{347 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);348}349350bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)351{352 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);353}354355CBlockIndex* InsertBlockIndex(uint256 hash)356{357 if (hash == 0)358 return NULL;359360 // Return existing361 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);362 if (mi != mapBlockIndex.end())363 return (*mi).second;364365 // Create new366 CBlockIndex* pindexNew = new CBlockIndex();367 if (!pindexNew)368 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");369 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;370 pindexNew->phashBlock = &((*mi).first);371372 return pindexNew;373}374375bool CTxDB::LoadBlockIndex()376{377 // Get database cursor378 Dbc* pcursor = GetCursor();379 if (!pcursor)380 return false;381382 // Load mapBlockIndex383 unsigned int fFlags = DB_SET_RANGE;384 loop385 {386 // Read next record387 CDataStream ssKey;388 if (fFlags == DB_SET_RANGE)389 ssKey << make_pair(string("blockindex"), uint256(0));390 CDataStream ssValue;391 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);392 fFlags = DB_NEXT;393 if (ret == DB_NOTFOUND)394 break;395 else if (ret != 0)396 return false;397398 // Unserialize399 string strType;400 ssKey >> strType;401 if (strType == "blockindex")402 {403 CDiskBlockIndex diskindex;404 ssValue >> diskindex;405406 // Construct block index object407 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());408 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);409 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);410 pindexNew->nFile = diskindex.nFile;411 pindexNew->nBlockPos = diskindex.nBlockPos;412 pindexNew->nHeight = diskindex.nHeight;413 pindexNew->nVersion = diskindex.nVersion;414 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;415 pindexNew->nTime = diskindex.nTime;416 pindexNew->nBits = diskindex.nBits;417 pindexNew->nNonce = diskindex.nNonce;418419 // Watch for genesis block420 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)421 pindexGenesisBlock = pindexNew;422 }423 else424 {425 break;426 }427 }428 pcursor->close();429430 // Calculate bnChainWork431 vector<pair<int, CBlockIndex*> > vSortedByHeight;432 vSortedByHeight.reserve(mapBlockIndex.size());433 foreach(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)434 {435 CBlockIndex* pindex = item.second;436 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));437 }438 sort(vSortedByHeight.begin(), vSortedByHeight.end());439 foreach(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)440 {441 CBlockIndex* pindex = item.second;442 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();443 }444445 // Load hashBestChain pointer to end of best chain446 if (!ReadHashBestChain(hashBestChain))447 {448 if (pindexGenesisBlock == NULL)449 return true;450 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");451 }452 if (!mapBlockIndex.count(hashBestChain))453 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");454 pindexBest = mapBlockIndex[hashBestChain];455 nBestHeight = pindexBest->nHeight;456 bnBestChainWork = pindexBest->bnChainWork;457 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);458459 // Load bnBestInvalidWork, OK if it doesn't exist460 ReadBestInvalidWork(bnBestInvalidWork);461462 return true;463}464465466467468469//470// CAddrDB471//472473bool CAddrDB::WriteAddress(const CAddress& addr)474{475 return Write(make_pair(string("addr"), addr.GetKey()), addr);476}477478bool CAddrDB::LoadAddresses()479{480 CRITICAL_BLOCK(cs_mapAddresses)481 {482 // Load user provided addresses483 CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");484 if (filein)485 {486 try487 {488 char psz[1000];489 while (fgets(psz, sizeof(psz), filein))490 {491 CAddress addr(psz, NODE_NETWORK);492 addr.nTime = 0; // so it won't relay unless successfully connected493 if (addr.IsValid())494 AddAddress(addr);495 }496 }497 catch (...) { }498 }499500 // Get cursor501 Dbc* pcursor = GetCursor();502 if (!pcursor)503 return false;504505 loop506 {507 // Read next record508 CDataStream ssKey;509 CDataStream ssValue;510 int ret = ReadAtCursor(pcursor, ssKey, ssValue);511 if (ret == DB_NOTFOUND)512 break;513 else if (ret != 0)514 return false;515516 // Unserialize517 string strType;518 ssKey >> strType;519 if (strType == "addr")520 {521 CAddress addr;522 ssValue >> addr;523 mapAddresses.insert(make_pair(addr.GetKey(), addr));524 }525 }526 pcursor->close();527528 printf("Loaded %d addresses\n", mapAddresses.size());529530 // Fix for possible bug that manifests in mapAddresses.count in irc.cpp,531 // just need to call count here and it doesn't happen there. The bug was the532 // pack pragma in irc.cpp and has been fixed, but I'm not in a hurry to delete this.533 mapAddresses.count(vector<unsigned char>(18));534 }535536 return true;537}538539bool LoadAddresses()540{541 return CAddrDB("cr+").LoadAddresses();542}543544545546547//548// CWalletDB549//550551bool CWalletDB::LoadWallet()552{553 vchDefaultKey.clear();554 int nFileVersion = 0;555556 // Modify defaults557#ifndef __WXMSW__558 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program559 fMinimizeToTray = false;560 fMinimizeOnClose = false;561#endif562563 //// todo: shouldn't we catch exceptions and try to recover and continue?564 CRITICAL_BLOCK(cs_mapKeys)565 CRITICAL_BLOCK(cs_mapWallet)566 {567 // Get cursor568 Dbc* pcursor = GetCursor();569 if (!pcursor)570 return false;571572 loop573 {574 // Read next record575 CDataStream ssKey;576 CDataStream ssValue;577 int ret = ReadAtCursor(pcursor, ssKey, ssValue);578 if (ret == DB_NOTFOUND)579 break;580 else if (ret != 0)581 return false;582583 // Unserialize584 // Taking advantage of the fact that pair serialization585 // is just the two items serialized one after the other586 string strType;587 ssKey >> strType;588 if (strType == "name")589 {590 string strAddress;591 ssKey >> strAddress;592 ssValue >> mapAddressBook[strAddress];593 }594 else if (strType == "tx")595 {596 uint256 hash;597 ssKey >> hash;598 CWalletTx& wtx = mapWallet[hash];599 ssValue >> wtx;600601 if (wtx.GetHash() != hash)602 printf("Error in wallet.dat, hash mismatch\n");603604 //// debug print605 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());606 //printf(" %12I64d %s %s %s\n",607 // wtx.vout[0].nValue,608 // DateTimeStrFormat("%x %H:%M:%S", wtx.nTime).c_str(),609 // wtx.hashBlock.ToString().substr(0,16).c_str(),610 // wtx.mapValue["message"].c_str());611 }612 else if (strType == "key" || strType == "wkey")613 {614 vector<unsigned char> vchPubKey;615 ssKey >> vchPubKey;616 CWalletKey wkey;617 if (strType == "key")618 ssValue >> wkey.vchPrivKey;619 else620 ssValue >> wkey;621622 mapKeys[vchPubKey] = wkey.vchPrivKey;623 mapPubKeys[Hash160(vchPubKey)] = vchPubKey;624 }625 else if (strType == "defaultkey")626 {627 ssValue >> vchDefaultKey;628 }629 else if (strType == "version")630 {631 ssValue >> nFileVersion;632 if (nFileVersion == 10300)633 nFileVersion = 300;634 }635 else if (strType == "setting")636 {637 string strKey;638 ssKey >> strKey;639640 // Menu state641 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;642643 // Options644 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;645 if (strKey == "addrIncoming") ssValue >> addrIncoming;646 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;647 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;648 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;649 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;650 if (strKey == "fUseProxy") ssValue >> fUseProxy;651 if (strKey == "addrProxy") ssValue >> addrProxy;652653 }654 }655 pcursor->close();656 }657658 printf("nFileVersion = %d\n", nFileVersion);659 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);660 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);661 printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());662 printf("fMinimizeToTray = %d\n", fMinimizeToTray);663 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);664 printf("fUseProxy = %d\n", fUseProxy);665 printf("addrProxy = %s\n", addrProxy.ToString().c_str());666667668 // The transaction fee setting won't be needed for many years to come.669 // Setting it to zero here in case they set it to something in an earlier version.670 if (nTransactionFee != 0)671 {672 nTransactionFee = 0;673 WriteSetting("nTransactionFee", nTransactionFee);674 }675676 // Upgrade677 if (nFileVersion < VERSION)678 {679 // Get rid of old debug.log file in current directory680 if (nFileVersion <= 105 && !pszSetDataDir[0])681 unlink("debug.log");682683 WriteVersion(VERSION);684 }685686 return true;687}688689bool LoadWallet(bool& fFirstRunRet)690{691 fFirstRunRet = false;692 if (!CWalletDB("cr+").LoadWallet())693 return false;694 fFirstRunRet = vchDefaultKey.empty();695696 if (mapKeys.count(vchDefaultKey))697 {698 // Set keyUser699 keyUser.SetPubKey(vchDefaultKey);700 keyUser.SetPrivKey(mapKeys[vchDefaultKey]);701 }702 else703 {704 // Create new keyUser and set as default key705 RandAddSeedPerfmon();706 keyUser.MakeNewKey();707 if (!AddKey(keyUser))708 return false;709 if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))710 return false;711 CWalletDB().WriteDefaultKey(keyUser.GetPubKey());712 }713714 CreateThread(ThreadFlushWalletDB, NULL);715 return true;716}717718void ThreadFlushWalletDB(void* parg)719{720 static bool fOneThread;721 if (fOneThread)722 return;723 fOneThread = true;724 if (mapArgs.count("-noflushwallet"))725 return;726727 unsigned int nLastSeen = nWalletDBUpdated;728 unsigned int nLastFlushed = nWalletDBUpdated;729 int64 nLastWalletUpdate = GetTime();730 while (!fShutdown)731 {732 Sleep(500);733734 if (nLastSeen != nWalletDBUpdated)735 {736 nLastSeen = nWalletDBUpdated;737 nLastWalletUpdate = GetTime();738 }739740 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)741 {742 TRY_CRITICAL_BLOCK(cs_db)743 {744 // Don't do this if any databases are in use745 int nRefCount = 0;746 map<string, int>::iterator mi = mapFileUseCount.begin();747 while (mi != mapFileUseCount.end())748 {749 nRefCount += (*mi).second;750 mi++;751 }752753 if (nRefCount == 0 && !fShutdown)754 {755 string strFile = "wallet.dat";756 map<string, int>::iterator mi = mapFileUseCount.find(strFile);757 if (mi != mapFileUseCount.end())758 {759 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());760 printf("Flushing wallet.dat\n");761 nLastFlushed = nWalletDBUpdated;762 int64 nStart = GetTimeMillis();763764 // Flush wallet.dat so it's self contained765 CloseDb(strFile);766 dbenv.txn_checkpoint(0, 0, 0);767 dbenv.lsn_reset(strFile.c_str(), 0);768769 mapFileUseCount.erase(mi++);770 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);771 }772 }773 }774 }775 }776}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
