1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 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(bool fRemoveLogFiles)
38 DbEnv(0).remove(GetDataDir().c_str(), 0);
42 filesystem::path datadir(GetDataDir());
43 filesystem::directory_iterator it(datadir / "database");
44 while (it != filesystem::directory_iterator())
46 const filesystem::path& p = it->path();
47 #if BOOST_FILESYSTEM_VERSION == 2
48 std::string f = p.filename();
50 std::string f = p.filename().generic_string();
52 if (f.find("log.") == 0)
53 filesystem::remove(p);
73 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
79 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
80 bool fCreate = strchr(pszMode, 'c');
81 unsigned int nFlags = DB_THREAD;
91 string strDataDir = GetDataDir();
92 string strLogDir = strDataDir + "/database";
93 filesystem::create_directory(strLogDir.c_str());
94 string strErrorFile = strDataDir + "/db.log";
95 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
97 dbenv.set_lg_dir(strLogDir.c_str());
98 dbenv.set_lg_max(10000000);
99 dbenv.set_lk_max_locks(10000);
100 dbenv.set_lk_max_objects(10000);
101 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
102 dbenv.set_flags(DB_AUTO_COMMIT, 1);
103 ret = dbenv.open(strDataDir.c_str(),
113 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
118 ++mapFileUseCount[strFile];
119 pdb = mapDb[strFile];
122 pdb = new Db(&dbenv, 0);
124 ret = pdb->open(NULL, // Txn pointer
126 "main", // Logical db name
127 DB_BTREE, // Database type
135 CRITICAL_BLOCK(cs_db)
136 --mapFileUseCount[strFile];
138 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
141 if (fCreate && !Exists(string("version")))
143 bool fTmp = fReadOnly;
145 WriteVersion(VERSION);
149 mapDb[strFile] = pdb;
159 vTxn.front()->abort();
163 // Flush database activity from memory pool to disk log
164 unsigned int nMinutes = 0;
167 if (strFile == "addr.dat")
169 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)
171 dbenv.txn_checkpoint(0, nMinutes, 0);
173 CRITICAL_BLOCK(cs_db)
174 --mapFileUseCount[strFile];
177 void static CloseDb(const string& strFile)
179 CRITICAL_BLOCK(cs_db)
181 if (mapDb[strFile] != NULL)
183 // Close the database handle
184 Db* pdb = mapDb[strFile];
187 mapDb[strFile] = NULL;
192 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
196 CRITICAL_BLOCK(cs_db)
198 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
200 // Flush log data to the dat file
202 dbenv.txn_checkpoint(0, 0, 0);
203 dbenv.lsn_reset(strFile.c_str(), 0);
204 mapFileUseCount.erase(strFile);
206 bool fSuccess = true;
207 printf("Rewriting %s...\n", strFile.c_str());
208 string strFileRes = strFile + ".rewrite";
209 CDB db(strFile.c_str(), "r");
210 Db* pdbCopy = new Db(&dbenv, 0);
212 int ret = pdbCopy->open(NULL, // Txn pointer
213 strFileRes.c_str(), // Filename
214 "main", // Logical db name
215 DB_BTREE, // Database type
220 printf("Cannot create database file %s\n", strFileRes.c_str());
224 Dbc* pcursor = db.GetCursor();
230 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
231 if (ret == DB_NOTFOUND)
240 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
242 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
248 Dbt datKey(&ssKey[0], ssKey.size());
249 Dbt datValue(&ssValue[0], ssValue.size());
250 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
256 Db* pdb = mapDb[strFile];
259 if (pdbCopy->close(0))
263 mapDb[strFile] = NULL;
268 if (dbA.remove(strFile.c_str(), NULL, 0))
271 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
275 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
285 void DBFlush(bool fShutdown, bool fRemoveLogFiles)
287 // Flush log data to the actual data file
288 // on all files that are not in use
289 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
292 CRITICAL_BLOCK(cs_db)
294 map<string, int>::iterator mi = mapFileUseCount.begin();
295 while (mi != mapFileUseCount.end())
297 string strFile = (*mi).first;
298 int nRefCount = (*mi).second;
299 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
302 // Move log data to the dat file
304 dbenv.txn_checkpoint(0, 0, 0);
305 printf("%s flush\n", strFile.c_str());
306 dbenv.lsn_reset(strFile.c_str(), 0);
307 mapFileUseCount.erase(mi++);
315 if (mapFileUseCount.empty())
317 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
318 EnvShutdown(fRemoveLogFiles);
333 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
337 return Read(make_pair(string("tx"), hash), txindex);
340 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
343 return Write(make_pair(string("tx"), hash), txindex);
346 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
351 uint256 hash = tx.GetHash();
352 CTxIndex txindex(pos, tx.vout.size());
353 return Write(make_pair(string("tx"), hash), txindex);
356 bool CTxDB::EraseTxIndex(const CTransaction& tx)
359 uint256 hash = tx.GetHash();
361 return Erase(make_pair(string("tx"), hash));
364 bool CTxDB::ContainsTx(uint256 hash)
367 return Exists(make_pair(string("tx"), hash));
370 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
376 Dbc* pcursor = GetCursor();
380 unsigned int fFlags = DB_SET_RANGE;
385 if (fFlags == DB_SET_RANGE)
386 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
388 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
390 if (ret == DB_NOTFOUND)
402 ssKey >> strType >> hashItem >> pos;
404 ssValue >> nItemHeight;
407 if (strType != "owner" || hashItem != hash160)
409 if (nItemHeight >= nMinHeight)
411 vtx.resize(vtx.size()+1);
412 if (!vtx.back().ReadFromDisk(pos))
424 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
428 if (!ReadTxIndex(hash, txindex))
430 return (tx.ReadFromDisk(txindex.pos));
433 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
436 return ReadDiskTx(hash, tx, txindex);
439 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
441 return ReadDiskTx(outpoint.hash, tx, txindex);
444 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
447 return ReadDiskTx(outpoint.hash, tx, txindex);
450 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
452 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
455 bool CTxDB::EraseBlockIndex(uint256 hash)
457 return Erase(make_pair(string("blockindex"), hash));
460 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
462 return Read(string("hashBestChain"), hashBestChain);
465 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
467 return Write(string("hashBestChain"), hashBestChain);
470 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
472 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
475 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
477 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
480 CBlockIndex static * InsertBlockIndex(uint256 hash)
486 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
487 if (mi != mapBlockIndex.end())
491 CBlockIndex* pindexNew = new CBlockIndex();
493 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
494 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
495 pindexNew->phashBlock = &((*mi).first);
500 bool CTxDB::LoadBlockIndex()
502 // Get database cursor
503 Dbc* pcursor = GetCursor();
507 // Load mapBlockIndex
508 unsigned int fFlags = DB_SET_RANGE;
513 if (fFlags == DB_SET_RANGE)
514 ssKey << make_pair(string("blockindex"), uint256(0));
516 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
518 if (ret == DB_NOTFOUND)
526 if (strType == "blockindex")
528 CDiskBlockIndex diskindex;
529 ssValue >> diskindex;
531 // Construct block index object
532 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
533 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
534 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
535 pindexNew->nFile = diskindex.nFile;
536 pindexNew->nBlockPos = diskindex.nBlockPos;
537 pindexNew->nHeight = diskindex.nHeight;
538 pindexNew->nVersion = diskindex.nVersion;
539 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
540 pindexNew->nTime = diskindex.nTime;
541 pindexNew->nBits = diskindex.nBits;
542 pindexNew->nNonce = diskindex.nNonce;
544 // Watch for genesis block
545 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
546 pindexGenesisBlock = pindexNew;
548 if (!pindexNew->CheckIndex())
549 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
558 // Calculate bnChainWork
559 vector<pair<int, CBlockIndex*> > vSortedByHeight;
560 vSortedByHeight.reserve(mapBlockIndex.size());
561 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
563 CBlockIndex* pindex = item.second;
564 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
566 sort(vSortedByHeight.begin(), vSortedByHeight.end());
567 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
569 CBlockIndex* pindex = item.second;
570 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
573 // Load hashBestChain pointer to end of best chain
574 if (!ReadHashBestChain(hashBestChain))
576 if (pindexGenesisBlock == NULL)
578 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
580 if (!mapBlockIndex.count(hashBestChain))
581 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
582 pindexBest = mapBlockIndex[hashBestChain];
583 nBestHeight = pindexBest->nHeight;
584 bnBestChainWork = pindexBest->bnChainWork;
585 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
587 // Load bnBestInvalidWork, OK if it doesn't exist
588 ReadBestInvalidWork(bnBestInvalidWork);
590 // Verify blocks in the best chain
591 CBlockIndex* pindexFork = NULL;
592 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
594 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
597 if (!block.ReadFromDisk(pindex))
598 return error("LoadBlockIndex() : block.ReadFromDisk failed");
599 if (!block.CheckBlock())
601 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
602 pindexFork = pindex->pprev;
607 // Reorg back to the fork
608 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
610 if (!block.ReadFromDisk(pindexFork))
611 return error("LoadBlockIndex() : block.ReadFromDisk failed");
613 block.SetBestChain(txdb, pindexFork);
627 bool CAddrDB::WriteAddress(const CAddress& addr)
629 return Write(make_pair(string("addr"), addr.GetKey()), addr);
632 bool CAddrDB::EraseAddress(const CAddress& addr)
634 return Erase(make_pair(string("addr"), addr.GetKey()));
637 bool CAddrDB::LoadAddresses()
639 CRITICAL_BLOCK(cs_mapAddresses)
642 Dbc* pcursor = GetCursor();
651 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
652 if (ret == DB_NOTFOUND)
660 if (strType == "addr")
664 mapAddresses.insert(make_pair(addr.GetKey(), addr));
669 printf("Loaded %d addresses\n", mapAddresses.size());
677 return CAddrDB("cr+").LoadAddresses();
687 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
690 return Write(make_pair(string("name"), strAddress), strName);
693 bool CWalletDB::EraseName(const string& strAddress)
695 // This should only be used for sending addresses, never for receiving addresses,
696 // receiving addresses must always have an address book entry if they're not change return.
698 return Erase(make_pair(string("name"), strAddress));
701 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
704 return Read(make_pair(string("acc"), strAccount), account);
707 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
709 return Write(make_pair(string("acc"), strAccount), account);
712 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
714 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
717 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
719 list<CAccountingEntry> entries;
720 ListAccountCreditDebit(strAccount, entries);
722 int64 nCreditDebit = 0;
723 BOOST_FOREACH (const CAccountingEntry& entry, entries)
724 nCreditDebit += entry.nCreditDebit;
729 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
731 bool fAllAccounts = (strAccount == "*");
733 Dbc* pcursor = GetCursor();
735 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
736 unsigned int fFlags = DB_SET_RANGE;
741 if (fFlags == DB_SET_RANGE)
742 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
744 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
746 if (ret == DB_NOTFOUND)
751 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
757 if (strType != "acentry")
759 CAccountingEntry acentry;
760 ssKey >> acentry.strAccount;
761 if (!fAllAccounts && acentry.strAccount != strAccount)
765 entries.push_back(acentry);
772 int CWalletDB::LoadWallet(CWallet* pwallet)
774 pwallet->vchDefaultKey.clear();
775 int nFileVersion = 0;
776 vector<uint256> vWalletUpgrade;
777 bool fIsEncrypted = false;
781 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
782 fMinimizeToTray = false;
783 fMinimizeOnClose = false;
786 //// todo: shouldn't we catch exceptions and try to recover and continue?
787 CRITICAL_BLOCK(pwallet->cs_wallet)
790 Dbc* pcursor = GetCursor();
799 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
800 if (ret == DB_NOTFOUND)
806 // Taking advantage of the fact that pair serialization
807 // is just the two items serialized one after the other
810 if (strType == "name")
814 ssValue >> pwallet->mapAddressBook[strAddress];
816 else if (strType == "tx")
820 CWalletTx& wtx = pwallet->mapWallet[hash];
822 wtx.pwallet = pwallet;
824 if (wtx.GetHash() != hash)
825 printf("Error in wallet.dat, hash mismatch\n");
827 // Undo serialize changes in 31600
828 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
830 if (!ssValue.empty())
834 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
835 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
836 wtx.fTimeReceivedIsTxTime = fTmp;
840 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
841 wtx.fTimeReceivedIsTxTime = 0;
843 vWalletUpgrade.push_back(hash);
847 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
848 //printf(" %12I64d %s %s %s\n",
849 // wtx.vout[0].nValue,
850 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
851 // wtx.hashBlock.ToString().substr(0,20).c_str(),
852 // wtx.mapValue["message"].c_str());
854 else if (strType == "acentry")
860 if (nNumber > nAccountingEntryNumber)
861 nAccountingEntryNumber = nNumber;
863 else if (strType == "key" || strType == "wkey")
865 vector<unsigned char> vchPubKey;
868 if (strType == "key")
872 key.SetPrivKey(pkey);
878 key.SetPrivKey(wkey.vchPrivKey);
880 if (!pwallet->LoadKey(key))
883 else if (strType == "mkey")
887 CMasterKey kMasterKey;
888 ssValue >> kMasterKey;
889 if(pwallet->mapMasterKeys.count(nID) != 0)
891 pwallet->mapMasterKeys[nID] = kMasterKey;
892 if (pwallet->nMasterKeyMaxID < nID)
893 pwallet->nMasterKeyMaxID = nID;
895 else if (strType == "ckey")
897 vector<unsigned char> vchPubKey;
899 vector<unsigned char> vchPrivKey;
900 ssValue >> vchPrivKey;
901 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
905 else if (strType == "defaultkey")
907 ssValue >> pwallet->vchDefaultKey;
909 else if (strType == "pool")
913 pwallet->setKeyPool.insert(nIndex);
915 else if (strType == "version")
917 ssValue >> nFileVersion;
918 if (nFileVersion == 10300)
921 else if (strType == "setting")
928 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
930 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
931 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
932 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
933 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
934 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
935 if (strKey == "fUseProxy") ssValue >> fUseProxy;
936 if (strKey == "addrProxy") ssValue >> addrProxy;
937 if (fHaveUPnP && strKey == "fUseUPnP") ssValue >> fUseUPnP;
939 else if (strType == "minversion")
942 ssValue >> nMinVersion;
943 if (nMinVersion > VERSION)
950 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
951 WriteTx(hash, pwallet->mapWallet[hash]);
953 printf("nFileVersion = %d\n", nFileVersion);
954 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
955 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
956 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
957 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
958 printf("fUseProxy = %d\n", fUseProxy);
959 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
961 printf("fUseUPnP = %d\n", fUseUPnP);
964 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
965 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
966 return DB_NEED_REWRITE;
968 if (nFileVersion < VERSION) // Update
970 // Get rid of old debug.log file in current directory
971 if (nFileVersion <= 105 && !pszSetDataDir[0])
974 WriteVersion(VERSION);
980 void ThreadFlushWalletDB(void* parg)
982 const string& strFile = ((const string*)parg)[0];
983 static bool fOneThread;
987 if (mapArgs.count("-noflushwallet"))
990 unsigned int nLastSeen = nWalletDBUpdated;
991 unsigned int nLastFlushed = nWalletDBUpdated;
992 int64 nLastWalletUpdate = GetTime();
997 if (nLastSeen != nWalletDBUpdated)
999 nLastSeen = nWalletDBUpdated;
1000 nLastWalletUpdate = GetTime();
1003 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1005 TRY_CRITICAL_BLOCK(cs_db)
1007 // Don't do this if any databases are in use
1009 map<string, int>::iterator mi = mapFileUseCount.begin();
1010 while (mi != mapFileUseCount.end())
1012 nRefCount += (*mi).second;
1016 if (nRefCount == 0 && !fShutdown)
1018 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1019 if (mi != mapFileUseCount.end())
1021 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1022 printf("Flushing wallet.dat\n");
1023 nLastFlushed = nWalletDBUpdated;
1024 int64 nStart = GetTimeMillis();
1026 // Flush wallet.dat so it's self contained
1028 dbenv.txn_checkpoint(0, 0, 0);
1029 dbenv.lsn_reset(strFile.c_str(), 0);
1031 mapFileUseCount.erase(mi++);
1032 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1040 bool BackupWallet(const CWallet& wallet, const string& strDest)
1042 if (!wallet.fFileBacked)
1046 CRITICAL_BLOCK(cs_db)
1048 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1050 // Flush log data to the dat file
1051 CloseDb(wallet.strWalletFile);
1052 dbenv.txn_checkpoint(0, 0, 0);
1053 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1054 mapFileUseCount.erase(wallet.strWalletFile);
1057 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1058 filesystem::path pathDest(strDest);
1059 if (filesystem::is_directory(pathDest))
1060 pathDest = pathDest / wallet.strWalletFile;
1061 #if BOOST_VERSION >= 104000
1062 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1064 filesystem::copy_file(pathSrc, pathDest);
1066 printf("copied wallet.dat to %s\n", pathDest.string().c_str());