1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
8 #include <boost/filesystem.hpp>
9 #include <boost/filesystem/fstream.hpp>
12 using namespace boost;
15 unsigned int nWalletDBUpdated;
16 uint64 nAccountingEntryNumber = 0;
24 static CCriticalSection cs_db;
25 static bool fDbEnvInit = false;
27 static map<string, int> mapFileUseCount;
28 static map<string, Db*> mapDb;
48 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
54 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
55 bool fCreate = strchr(pszMode, 'c');
56 unsigned int nFlags = DB_THREAD;
66 string strDataDir = GetDataDir();
67 string strLogDir = strDataDir + "/database";
68 filesystem::create_directory(strLogDir.c_str());
69 string strErrorFile = strDataDir + "/db.log";
70 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
72 dbenv.set_lg_dir(strLogDir.c_str());
73 dbenv.set_lg_max(10000000);
74 dbenv.set_lk_max_locks(10000);
75 dbenv.set_lk_max_objects(10000);
76 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
77 dbenv.set_flags(DB_AUTO_COMMIT, 1);
78 ret = dbenv.open(strDataDir.c_str(),
88 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
93 ++mapFileUseCount[strFile];
97 pdb = new Db(&dbenv, 0);
99 ret = pdb->open(NULL, // Txn pointer
101 "main", // Logical db name
102 DB_BTREE, // Database type
110 CRITICAL_BLOCK(cs_db)
111 --mapFileUseCount[strFile];
113 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
116 if (fCreate && !Exists(string("version")))
118 bool fTmp = fReadOnly;
120 WriteVersion(VERSION);
124 mapDb[strFile] = pdb;
134 vTxn.front()->abort();
138 // Flush database activity from memory pool to disk log
139 unsigned int nMinutes = 0;
142 if (strFile == "addr.dat")
144 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)
146 dbenv.txn_checkpoint(0, nMinutes, 0);
148 CRITICAL_BLOCK(cs_db)
149 --mapFileUseCount[strFile];
152 void static CloseDb(const string& strFile)
154 CRITICAL_BLOCK(cs_db)
156 if (mapDb[strFile] != NULL)
158 // Close the database handle
159 Db* pdb = mapDb[strFile];
162 mapDb[strFile] = NULL;
167 void DBFlush(bool fShutdown)
169 // Flush log data to the actual data file
170 // on all files that are not in use
171 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
174 CRITICAL_BLOCK(cs_db)
176 map<string, int>::iterator mi = mapFileUseCount.begin();
177 while (mi != mapFileUseCount.end())
179 string strFile = (*mi).first;
180 int nRefCount = (*mi).second;
181 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
184 // Move log data to the dat file
186 dbenv.txn_checkpoint(0, 0, 0);
187 printf("%s flush\n", strFile.c_str());
188 dbenv.lsn_reset(strFile.c_str(), 0);
189 mapFileUseCount.erase(mi++);
197 if (mapFileUseCount.empty())
198 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
214 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
218 return Read(make_pair(string("tx"), hash), txindex);
221 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
224 return Write(make_pair(string("tx"), hash), txindex);
227 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
232 uint256 hash = tx.GetHash();
233 CTxIndex txindex(pos, tx.vout.size());
234 return Write(make_pair(string("tx"), hash), txindex);
237 bool CTxDB::EraseTxIndex(const CTransaction& tx)
240 uint256 hash = tx.GetHash();
242 return Erase(make_pair(string("tx"), hash));
245 bool CTxDB::ContainsTx(uint256 hash)
248 return Exists(make_pair(string("tx"), hash));
251 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
257 Dbc* pcursor = GetCursor();
261 unsigned int fFlags = DB_SET_RANGE;
266 if (fFlags == DB_SET_RANGE)
267 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
269 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
271 if (ret == DB_NOTFOUND)
283 ssKey >> strType >> hashItem >> pos;
285 ssValue >> nItemHeight;
288 if (strType != "owner" || hashItem != hash160)
290 if (nItemHeight >= nMinHeight)
292 vtx.resize(vtx.size()+1);
293 if (!vtx.back().ReadFromDisk(pos))
305 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
309 if (!ReadTxIndex(hash, txindex))
311 return (tx.ReadFromDisk(txindex.pos));
314 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
317 return ReadDiskTx(hash, tx, txindex);
320 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
322 return ReadDiskTx(outpoint.hash, tx, txindex);
325 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
328 return ReadDiskTx(outpoint.hash, tx, txindex);
331 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
333 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
336 bool CTxDB::EraseBlockIndex(uint256 hash)
338 return Erase(make_pair(string("blockindex"), hash));
341 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
343 return Read(string("hashBestChain"), hashBestChain);
346 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
348 return Write(string("hashBestChain"), hashBestChain);
351 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
353 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
356 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
358 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
361 CBlockIndex static * InsertBlockIndex(uint256 hash)
367 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
368 if (mi != mapBlockIndex.end())
372 CBlockIndex* pindexNew = new CBlockIndex();
374 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
375 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
376 pindexNew->phashBlock = &((*mi).first);
381 bool CTxDB::LoadBlockIndex()
383 // Get database cursor
384 Dbc* pcursor = GetCursor();
388 // Load mapBlockIndex
389 unsigned int fFlags = DB_SET_RANGE;
394 if (fFlags == DB_SET_RANGE)
395 ssKey << make_pair(string("blockindex"), uint256(0));
397 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
399 if (ret == DB_NOTFOUND)
407 if (strType == "blockindex")
409 CDiskBlockIndex diskindex;
410 ssValue >> diskindex;
412 // Construct block index object
413 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
414 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
415 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
416 pindexNew->nFile = diskindex.nFile;
417 pindexNew->nBlockPos = diskindex.nBlockPos;
418 pindexNew->nHeight = diskindex.nHeight;
419 pindexNew->nVersion = diskindex.nVersion;
420 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
421 pindexNew->nTime = diskindex.nTime;
422 pindexNew->nBits = diskindex.nBits;
423 pindexNew->nNonce = diskindex.nNonce;
425 // Watch for genesis block
426 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
427 pindexGenesisBlock = pindexNew;
429 if (!pindexNew->CheckIndex())
430 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
439 // Calculate bnChainWork
440 vector<pair<int, CBlockIndex*> > vSortedByHeight;
441 vSortedByHeight.reserve(mapBlockIndex.size());
442 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
444 CBlockIndex* pindex = item.second;
445 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
447 sort(vSortedByHeight.begin(), vSortedByHeight.end());
448 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
450 CBlockIndex* pindex = item.second;
451 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
454 // Load hashBestChain pointer to end of best chain
455 if (!ReadHashBestChain(hashBestChain))
457 if (pindexGenesisBlock == NULL)
459 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
461 if (!mapBlockIndex.count(hashBestChain))
462 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
463 pindexBest = mapBlockIndex[hashBestChain];
464 nBestHeight = pindexBest->nHeight;
465 bnBestChainWork = pindexBest->bnChainWork;
466 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
468 // Load bnBestInvalidWork, OK if it doesn't exist
469 ReadBestInvalidWork(bnBestInvalidWork);
471 // Verify blocks in the best chain
472 CBlockIndex* pindexFork = NULL;
473 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
475 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
478 if (!block.ReadFromDisk(pindex))
479 return error("LoadBlockIndex() : block.ReadFromDisk failed");
480 if (!block.CheckBlock())
482 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
483 pindexFork = pindex->pprev;
488 // Reorg back to the fork
489 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
491 if (!block.ReadFromDisk(pindexFork))
492 return error("LoadBlockIndex() : block.ReadFromDisk failed");
494 block.SetBestChain(txdb, pindexFork);
508 bool CAddrDB::WriteAddress(const CAddress& addr)
510 return Write(make_pair(string("addr"), addr.GetKey()), addr);
513 bool CAddrDB::EraseAddress(const CAddress& addr)
515 return Erase(make_pair(string("addr"), addr.GetKey()));
518 bool CAddrDB::LoadAddresses()
520 CRITICAL_BLOCK(cs_mapAddresses)
522 // Load user provided addresses
523 CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
529 while (fgets(psz, sizeof(psz), filein))
531 CAddress addr(psz, NODE_NETWORK);
532 addr.nTime = 0; // so it won't relay unless successfully connected
541 Dbc* pcursor = GetCursor();
550 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
551 if (ret == DB_NOTFOUND)
559 if (strType == "addr")
563 mapAddresses.insert(make_pair(addr.GetKey(), addr));
568 printf("Loaded %d addresses\n", mapAddresses.size());
576 return CAddrDB("cr+").LoadAddresses();
586 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
589 return Write(make_pair(string("name"), strAddress), strName);
592 bool CWalletDB::EraseName(const string& strAddress)
594 // This should only be used for sending addresses, never for receiving addresses,
595 // receiving addresses must always have an address book entry if they're not change return.
597 return Erase(make_pair(string("name"), strAddress));
600 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
603 return Read(make_pair(string("acc"), strAccount), account);
606 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
608 return Write(make_pair(string("acc"), strAccount), account);
611 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
613 return Write(make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
616 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
618 list<CAccountingEntry> entries;
619 ListAccountCreditDebit(strAccount, entries);
621 int64 nCreditDebit = 0;
622 BOOST_FOREACH (const CAccountingEntry& entry, entries)
623 nCreditDebit += entry.nCreditDebit;
628 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
630 int64 nCreditDebit = 0;
632 bool fAllAccounts = (strAccount == "*");
634 Dbc* pcursor = GetCursor();
636 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
637 unsigned int fFlags = DB_SET_RANGE;
642 if (fFlags == DB_SET_RANGE)
643 ssKey << make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
645 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
647 if (ret == DB_NOTFOUND)
652 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
658 if (strType != "acentry")
660 CAccountingEntry acentry;
661 ssKey >> acentry.strAccount;
662 if (!fAllAccounts && acentry.strAccount != strAccount)
666 entries.push_back(acentry);
673 bool CWalletDB::LoadWallet(CWallet* pwallet)
675 pwallet->vchDefaultKey.clear();
676 int nFileVersion = 0;
677 vector<uint256> vWalletUpgrade;
681 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
682 fMinimizeToTray = false;
683 fMinimizeOnClose = false;
686 //// todo: shouldn't we catch exceptions and try to recover and continue?
687 CRITICAL_BLOCK(pwallet->cs_mapWallet)
688 CRITICAL_BLOCK(pwallet->cs_KeyStore)
691 Dbc* pcursor = GetCursor();
700 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
701 if (ret == DB_NOTFOUND)
707 // Taking advantage of the fact that pair serialization
708 // is just the two items serialized one after the other
711 if (strType == "name")
715 ssValue >> pwallet->mapAddressBook[strAddress];
717 else if (strType == "tx")
721 CWalletTx& wtx = pwallet->mapWallet[hash];
723 wtx.pwallet = pwallet;
725 if (wtx.GetHash() != hash)
726 printf("Error in wallet.dat, hash mismatch\n");
728 // Undo serialize changes in 31600
729 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
731 if (!ssValue.empty())
735 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
736 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
737 wtx.fTimeReceivedIsTxTime = fTmp;
741 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
742 wtx.fTimeReceivedIsTxTime = 0;
744 vWalletUpgrade.push_back(hash);
748 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
749 //printf(" %12I64d %s %s %s\n",
750 // wtx.vout[0].nValue,
751 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
752 // wtx.hashBlock.ToString().substr(0,20).c_str(),
753 // wtx.mapValue["message"].c_str());
755 else if (strType == "acentry")
761 if (nNumber > nAccountingEntryNumber)
762 nAccountingEntryNumber = nNumber;
764 else if (strType == "key" || strType == "wkey")
766 vector<unsigned char> vchPubKey;
769 if (strType == "key")
773 key.SetPrivKey(pkey);
779 key.SetPrivKey(wkey.vchPrivKey);
781 pwallet->LoadKey(key);
783 else if (strType == "defaultkey")
785 ssValue >> pwallet->vchDefaultKey;
787 else if (strType == "pool")
791 pwallet->setKeyPool.insert(nIndex);
793 else if (strType == "version")
795 ssValue >> nFileVersion;
796 if (nFileVersion == 10300)
799 else if (strType == "setting")
806 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
808 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
809 if (strKey == "addrIncoming") ssValue >> addrIncoming;
810 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
811 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
812 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
813 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
814 if (strKey == "fUseProxy") ssValue >> fUseProxy;
815 if (strKey == "addrProxy") ssValue >> addrProxy;
816 if (fHaveUPnP && strKey == "fUseUPnP") ssValue >> fUseUPnP;
822 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
823 WriteTx(hash, pwallet->mapWallet[hash]);
825 printf("nFileVersion = %d\n", nFileVersion);
826 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
827 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
828 printf("addrIncoming = %s\n", addrIncoming.ToString().c_str());
829 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
830 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
831 printf("fUseProxy = %d\n", fUseProxy);
832 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
834 printf("fUseUPnP = %d\n", fUseUPnP);
838 if (nFileVersion < VERSION)
840 // Get rid of old debug.log file in current directory
841 if (nFileVersion <= 105 && !pszSetDataDir[0])
844 WriteVersion(VERSION);
851 void ThreadFlushWalletDB(void* parg)
853 const string& strFile = ((const string*)parg)[0];
854 static bool fOneThread;
858 if (mapArgs.count("-noflushwallet"))
861 unsigned int nLastSeen = nWalletDBUpdated;
862 unsigned int nLastFlushed = nWalletDBUpdated;
863 int64 nLastWalletUpdate = GetTime();
868 if (nLastSeen != nWalletDBUpdated)
870 nLastSeen = nWalletDBUpdated;
871 nLastWalletUpdate = GetTime();
874 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
876 TRY_CRITICAL_BLOCK(cs_db)
878 // Don't do this if any databases are in use
880 map<string, int>::iterator mi = mapFileUseCount.begin();
881 while (mi != mapFileUseCount.end())
883 nRefCount += (*mi).second;
887 if (nRefCount == 0 && !fShutdown)
889 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
890 if (mi != mapFileUseCount.end())
892 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
893 printf("Flushing wallet.dat\n");
894 nLastFlushed = nWalletDBUpdated;
895 int64 nStart = GetTimeMillis();
897 // Flush wallet.dat so it's self contained
899 dbenv.txn_checkpoint(0, 0, 0);
900 dbenv.lsn_reset(strFile.c_str(), 0);
902 mapFileUseCount.erase(mi++);
903 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
911 bool BackupWallet(const CWallet& wallet, const string& strDest)
913 if (!wallet.fFileBacked)
917 CRITICAL_BLOCK(cs_db)
919 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
921 // Flush log data to the dat file
922 CloseDb(wallet.strWalletFile);
923 dbenv.txn_checkpoint(0, 0, 0);
924 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
925 mapFileUseCount.erase(wallet.strWalletFile);
928 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
929 filesystem::path pathDest(strDest);
930 if (filesystem::is_directory(pathDest))
931 pathDest = pathDest / wallet.strWalletFile;
932 #if BOOST_VERSION >= 104000
933 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
935 filesystem::copy_file(pathSrc, pathDest);
937 printf("copied wallet.dat to %s\n", pathDest.string().c_str());