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 license.txt or http://www.opensource.org/licenses/mit-license.php.
9 #include <boost/filesystem.hpp>
10 #include <boost/filesystem/fstream.hpp>
13 using namespace boost;
16 unsigned int nWalletDBUpdated;
17 uint64 nAccountingEntryNumber = 0;
25 static CCriticalSection cs_db;
26 static bool fDbEnvInit = false;
28 static map<string, int> mapFileUseCount;
29 static map<string, Db*> mapDb;
31 static void EnvShutdown()
41 catch (const DbException& e)
43 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
45 DbEnv(0).remove(GetDataDir().c_str(), 0);
62 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
68 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
69 bool fCreate = strchr(pszMode, 'c');
70 unsigned int nFlags = DB_THREAD;
80 string strDataDir = GetDataDir();
81 string strLogDir = strDataDir + "/database";
82 filesystem::create_directory(strLogDir.c_str());
83 string strErrorFile = strDataDir + "/db.log";
84 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
86 dbenv.set_lg_dir(strLogDir.c_str());
87 dbenv.set_lg_max(10000000);
88 dbenv.set_lk_max_locks(10000);
89 dbenv.set_lk_max_objects(10000);
90 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
91 dbenv.set_flags(DB_AUTO_COMMIT, 1);
92 ret = dbenv.open(strDataDir.c_str(),
102 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
107 ++mapFileUseCount[strFile];
108 pdb = mapDb[strFile];
111 pdb = new Db(&dbenv, 0);
113 ret = pdb->open(NULL, // Txn pointer
115 "main", // Logical db name
116 DB_BTREE, // Database type
124 CRITICAL_BLOCK(cs_db)
125 --mapFileUseCount[strFile];
127 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
130 if (fCreate && !Exists(string("version")))
132 bool fTmp = fReadOnly;
134 WriteVersion(VERSION);
138 mapDb[strFile] = pdb;
148 vTxn.front()->abort();
152 // Flush database activity from memory pool to disk log
153 unsigned int nMinutes = 0;
156 if (strFile == "addr.dat")
158 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)
160 dbenv.txn_checkpoint(0, nMinutes, 0);
162 CRITICAL_BLOCK(cs_db)
163 --mapFileUseCount[strFile];
166 void static CloseDb(const string& strFile)
168 CRITICAL_BLOCK(cs_db)
170 if (mapDb[strFile] != NULL)
172 // Close the database handle
173 Db* pdb = mapDb[strFile];
176 mapDb[strFile] = NULL;
181 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
185 CRITICAL_BLOCK(cs_db)
187 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
189 // Flush log data to the dat file
191 dbenv.txn_checkpoint(0, 0, 0);
192 dbenv.lsn_reset(strFile.c_str(), 0);
193 mapFileUseCount.erase(strFile);
195 bool fSuccess = true;
196 printf("Rewriting %s...\n", strFile.c_str());
197 string strFileRes = strFile + ".rewrite";
198 { // surround usage of db with extra {}
199 CDB db(strFile.c_str(), "r");
200 Db* pdbCopy = new Db(&dbenv, 0);
202 int ret = pdbCopy->open(NULL, // Txn pointer
203 strFileRes.c_str(), // Filename
204 "main", // Logical db name
205 DB_BTREE, // Database type
210 printf("Cannot create database file %s\n", strFileRes.c_str());
214 Dbc* pcursor = db.GetCursor();
220 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
221 if (ret == DB_NOTFOUND)
233 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
235 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
241 Dbt datKey(&ssKey[0], ssKey.size());
242 Dbt datValue(&ssValue[0], ssValue.size());
243 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
251 if (pdbCopy->close(0))
259 if (dbA.remove(strFile.c_str(), NULL, 0))
262 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
266 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
276 void DBFlush(bool fShutdown)
278 // Flush log data to the actual data file
279 // on all files that are not in use
280 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
283 CRITICAL_BLOCK(cs_db)
285 map<string, int>::iterator mi = mapFileUseCount.begin();
286 while (mi != mapFileUseCount.end())
288 string strFile = (*mi).first;
289 int nRefCount = (*mi).second;
290 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
293 // Move log data to the dat file
295 dbenv.txn_checkpoint(0, 0, 0);
296 printf("%s flush\n", strFile.c_str());
297 dbenv.lsn_reset(strFile.c_str(), 0);
298 mapFileUseCount.erase(mi++);
306 if (mapFileUseCount.empty())
308 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
324 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
328 return Read(make_pair(string("tx"), hash), txindex);
331 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
334 return Write(make_pair(string("tx"), hash), txindex);
337 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
342 uint256 hash = tx.GetHash();
343 CTxIndex txindex(pos, tx.vout.size());
344 return Write(make_pair(string("tx"), hash), txindex);
347 bool CTxDB::EraseTxIndex(const CTransaction& tx)
350 uint256 hash = tx.GetHash();
352 return Erase(make_pair(string("tx"), hash));
355 bool CTxDB::ContainsTx(uint256 hash)
358 return Exists(make_pair(string("tx"), hash));
361 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
367 Dbc* pcursor = GetCursor();
371 unsigned int fFlags = DB_SET_RANGE;
376 if (fFlags == DB_SET_RANGE)
377 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
379 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
381 if (ret == DB_NOTFOUND)
393 ssKey >> strType >> hashItem >> pos;
395 ssValue >> nItemHeight;
398 if (strType != "owner" || hashItem != hash160)
400 if (nItemHeight >= nMinHeight)
402 vtx.resize(vtx.size()+1);
403 if (!vtx.back().ReadFromDisk(pos))
415 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
419 if (!ReadTxIndex(hash, txindex))
421 return (tx.ReadFromDisk(txindex.pos));
424 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
427 return ReadDiskTx(hash, tx, txindex);
430 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
432 return ReadDiskTx(outpoint.hash, tx, txindex);
435 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
438 return ReadDiskTx(outpoint.hash, tx, txindex);
441 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
443 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
446 bool CTxDB::EraseBlockIndex(uint256 hash)
448 return Erase(make_pair(string("blockindex"), hash));
451 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
453 return Read(string("hashBestChain"), hashBestChain);
456 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
458 return Write(string("hashBestChain"), hashBestChain);
461 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
463 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
466 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
468 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
471 CBlockIndex static * InsertBlockIndex(uint256 hash)
477 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
478 if (mi != mapBlockIndex.end())
482 CBlockIndex* pindexNew = new CBlockIndex();
484 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
485 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
486 pindexNew->phashBlock = &((*mi).first);
491 bool CTxDB::LoadBlockIndex()
493 // Get database cursor
494 Dbc* pcursor = GetCursor();
498 // Load mapBlockIndex
499 unsigned int fFlags = DB_SET_RANGE;
504 if (fFlags == DB_SET_RANGE)
505 ssKey << make_pair(string("blockindex"), uint256(0));
507 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
509 if (ret == DB_NOTFOUND)
517 if (strType == "blockindex")
519 CDiskBlockIndex diskindex;
520 ssValue >> diskindex;
522 // Construct block index object
523 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
524 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
525 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
526 pindexNew->nFile = diskindex.nFile;
527 pindexNew->nBlockPos = diskindex.nBlockPos;
528 pindexNew->nHeight = diskindex.nHeight;
529 pindexNew->nVersion = diskindex.nVersion;
530 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
531 pindexNew->nTime = diskindex.nTime;
532 pindexNew->nBits = diskindex.nBits;
533 pindexNew->nNonce = diskindex.nNonce;
535 // Watch for genesis block
536 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
537 pindexGenesisBlock = pindexNew;
539 if (!pindexNew->CheckIndex())
540 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
549 // Calculate bnChainWork
550 vector<pair<int, CBlockIndex*> > vSortedByHeight;
551 vSortedByHeight.reserve(mapBlockIndex.size());
552 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
554 CBlockIndex* pindex = item.second;
555 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
557 sort(vSortedByHeight.begin(), vSortedByHeight.end());
558 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
560 CBlockIndex* pindex = item.second;
561 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
564 // Load hashBestChain pointer to end of best chain
565 if (!ReadHashBestChain(hashBestChain))
567 if (pindexGenesisBlock == NULL)
569 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
571 if (!mapBlockIndex.count(hashBestChain))
572 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
573 pindexBest = mapBlockIndex[hashBestChain];
574 nBestHeight = pindexBest->nHeight;
575 bnBestChainWork = pindexBest->bnChainWork;
576 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
578 // Load bnBestInvalidWork, OK if it doesn't exist
579 ReadBestInvalidWork(bnBestInvalidWork);
581 // Verify blocks in the best chain
582 CBlockIndex* pindexFork = NULL;
583 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
585 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
588 if (!block.ReadFromDisk(pindex))
589 return error("LoadBlockIndex() : block.ReadFromDisk failed");
590 if (!block.CheckBlock())
592 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
593 pindexFork = pindex->pprev;
598 // Reorg back to the fork
599 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
601 if (!block.ReadFromDisk(pindexFork))
602 return error("LoadBlockIndex() : block.ReadFromDisk failed");
604 block.SetBestChain(txdb, pindexFork);
618 bool CAddrDB::WriteAddress(const CAddress& addr)
620 return Write(make_pair(string("addr"), addr.GetKey()), addr);
623 bool CAddrDB::EraseAddress(const CAddress& addr)
625 return Erase(make_pair(string("addr"), addr.GetKey()));
628 bool CAddrDB::LoadAddresses()
630 CRITICAL_BLOCK(cs_mapAddresses)
632 // Load user provided addresses
633 CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
639 while (fgets(psz, sizeof(psz), filein))
641 CAddress addr(psz, false, NODE_NETWORK);
642 addr.nTime = 0; // so it won't relay unless successfully connected
651 Dbc* pcursor = GetCursor();
660 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
661 if (ret == DB_NOTFOUND)
669 if (strType == "addr")
673 mapAddresses.insert(make_pair(addr.GetKey(), addr));
678 printf("Loaded %d addresses\n", mapAddresses.size());
686 return CAddrDB("cr+").LoadAddresses();
696 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
699 return Write(make_pair(string("name"), strAddress), strName);
702 bool CWalletDB::EraseName(const string& strAddress)
704 // This should only be used for sending addresses, never for receiving addresses,
705 // receiving addresses must always have an address book entry if they're not change return.
707 return Erase(make_pair(string("name"), strAddress));
710 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
713 return Read(make_pair(string("acc"), strAccount), account);
716 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
718 return Write(make_pair(string("acc"), strAccount), account);
721 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
723 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
726 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
728 list<CAccountingEntry> entries;
729 ListAccountCreditDebit(strAccount, entries);
731 int64 nCreditDebit = 0;
732 BOOST_FOREACH (const CAccountingEntry& entry, entries)
733 nCreditDebit += entry.nCreditDebit;
738 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
740 bool fAllAccounts = (strAccount == "*");
742 Dbc* pcursor = GetCursor();
744 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
745 unsigned int fFlags = DB_SET_RANGE;
750 if (fFlags == DB_SET_RANGE)
751 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
753 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
755 if (ret == DB_NOTFOUND)
760 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
766 if (strType != "acentry")
768 CAccountingEntry acentry;
769 ssKey >> acentry.strAccount;
770 if (!fAllAccounts && acentry.strAccount != strAccount)
774 entries.push_back(acentry);
781 int CWalletDB::LoadWallet(CWallet* pwallet)
783 pwallet->vchDefaultKey.clear();
784 int nFileVersion = 0;
785 vector<uint256> vWalletUpgrade;
786 bool fIsEncrypted = false;
790 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
791 fMinimizeToTray = false;
792 fMinimizeOnClose = false;
795 //// todo: shouldn't we catch exceptions and try to recover and continue?
796 CRITICAL_BLOCK(pwallet->cs_wallet)
799 if (Read((string)"minversion", nMinVersion))
801 if (nMinVersion > VERSION)
806 Dbc* pcursor = GetCursor();
809 printf("Error getting wallet database cursor\n");
818 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
819 if (ret == DB_NOTFOUND)
823 printf("Error reading next record from wallet database\n");
828 // Taking advantage of the fact that pair serialization
829 // is just the two items serialized one after the other
832 if (strType == "name")
836 ssValue >> pwallet->mapAddressBook[strAddress];
838 else if (strType == "tx")
842 CWalletTx& wtx = pwallet->mapWallet[hash];
844 wtx.pwallet = pwallet;
846 if (wtx.GetHash() != hash)
847 printf("Error in wallet.dat, hash mismatch\n");
849 // Undo serialize changes in 31600
850 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
852 if (!ssValue.empty())
856 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
857 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
858 wtx.fTimeReceivedIsTxTime = fTmp;
862 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
863 wtx.fTimeReceivedIsTxTime = 0;
865 vWalletUpgrade.push_back(hash);
869 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
870 //printf(" %12I64d %s %s %s\n",
871 // wtx.vout[0].nValue,
872 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
873 // wtx.hashBlock.ToString().substr(0,20).c_str(),
874 // wtx.mapValue["message"].c_str());
876 else if (strType == "acentry")
882 if (nNumber > nAccountingEntryNumber)
883 nAccountingEntryNumber = nNumber;
885 else if (strType == "key" || strType == "wkey")
887 vector<unsigned char> vchPubKey;
890 if (strType == "key")
894 key.SetPrivKey(pkey);
895 if (key.GetPubKey() != vchPubKey)
897 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
902 printf("Error reading wallet database: invalid CPrivKey\n");
910 key.SetPrivKey(wkey.vchPrivKey);
911 if (key.GetPubKey() != vchPubKey)
913 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
918 printf("Error reading wallet database: invalid CWalletKey\n");
922 if (!pwallet->LoadKey(key))
924 printf("Error reading wallet database: LoadKey failed\n");
928 else if (strType == "mkey")
932 CMasterKey kMasterKey;
933 ssValue >> kMasterKey;
934 if(pwallet->mapMasterKeys.count(nID) != 0)
936 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
939 pwallet->mapMasterKeys[nID] = kMasterKey;
940 if (pwallet->nMasterKeyMaxID < nID)
941 pwallet->nMasterKeyMaxID = nID;
943 else if (strType == "ckey")
945 vector<unsigned char> vchPubKey;
947 vector<unsigned char> vchPrivKey;
948 ssValue >> vchPrivKey;
949 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
951 printf("Error reading wallet database: LoadCryptedKey failed\n");
956 else if (strType == "defaultkey")
958 ssValue >> pwallet->vchDefaultKey;
960 else if (strType == "pool")
964 pwallet->setKeyPool.insert(nIndex);
966 else if (strType == "version")
968 ssValue >> nFileVersion;
969 if (nFileVersion == 10300)
972 else if (strType == "setting")
979 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
981 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
982 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
983 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
984 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
985 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
986 if (strKey == "fUseProxy") ssValue >> fUseProxy;
987 if (strKey == "addrProxy") ssValue >> addrProxy;
988 if (fHaveUPnP && strKey == "fUseUPnP") ssValue >> fUseUPnP;
994 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
995 WriteTx(hash, pwallet->mapWallet[hash]);
997 printf("nFileVersion = %d\n", nFileVersion);
998 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
999 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
1000 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
1001 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
1002 printf("fUseProxy = %d\n", fUseProxy);
1003 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
1005 printf("fUseUPnP = %d\n", fUseUPnP);
1008 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1009 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1010 return DB_NEED_REWRITE;
1012 if (nFileVersion < VERSION) // Update
1014 // Get rid of old debug.log file in current directory
1015 if (nFileVersion <= 105 && !pszSetDataDir[0])
1016 unlink("debug.log");
1018 WriteVersion(VERSION);
1024 void ThreadFlushWalletDB(void* parg)
1026 const string& strFile = ((const string*)parg)[0];
1027 static bool fOneThread;
1031 if (mapArgs.count("-noflushwallet"))
1034 unsigned int nLastSeen = nWalletDBUpdated;
1035 unsigned int nLastFlushed = nWalletDBUpdated;
1036 int64 nLastWalletUpdate = GetTime();
1041 if (nLastSeen != nWalletDBUpdated)
1043 nLastSeen = nWalletDBUpdated;
1044 nLastWalletUpdate = GetTime();
1047 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1049 TRY_CRITICAL_BLOCK(cs_db)
1051 // Don't do this if any databases are in use
1053 map<string, int>::iterator mi = mapFileUseCount.begin();
1054 while (mi != mapFileUseCount.end())
1056 nRefCount += (*mi).second;
1060 if (nRefCount == 0 && !fShutdown)
1062 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1063 if (mi != mapFileUseCount.end())
1065 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1066 printf("Flushing wallet.dat\n");
1067 nLastFlushed = nWalletDBUpdated;
1068 int64 nStart = GetTimeMillis();
1070 // Flush wallet.dat so it's self contained
1072 dbenv.txn_checkpoint(0, 0, 0);
1073 dbenv.lsn_reset(strFile.c_str(), 0);
1075 mapFileUseCount.erase(mi++);
1076 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1084 bool BackupWallet(const CWallet& wallet, const string& strDest)
1086 if (!wallet.fFileBacked)
1090 CRITICAL_BLOCK(cs_db)
1092 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1094 // Flush log data to the dat file
1095 CloseDb(wallet.strWalletFile);
1096 dbenv.txn_checkpoint(0, 0, 0);
1097 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1098 mapFileUseCount.erase(wallet.strWalletFile);
1101 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1102 filesystem::path pathDest(strDest);
1103 if (filesystem::is_directory(pathDest))
1104 pathDest = pathDest / wallet.strWalletFile;
1105 #if BOOST_VERSION >= 104000
1106 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1108 filesystem::copy_file(pathSrc, pathDest);
1110 printf("copied wallet.dat to %s\n", pathDest.string().c_str());