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()
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 CDB db(strFile.c_str(), "r");
199 Db* pdbCopy = new Db(&dbenv, 0);
201 int ret = pdbCopy->open(NULL, // Txn pointer
202 strFileRes.c_str(), // Filename
203 "main", // Logical db name
204 DB_BTREE, // Database type
209 printf("Cannot create database file %s\n", strFileRes.c_str());
213 Dbc* pcursor = db.GetCursor();
219 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
220 if (ret == DB_NOTFOUND)
232 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
234 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
240 Dbt datKey(&ssKey[0], ssKey.size());
241 Dbt datValue(&ssValue[0], ssValue.size());
242 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
250 if (pdbCopy->close(0))
257 if (dbA.remove(strFile.c_str(), NULL, 0))
260 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
264 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
274 void DBFlush(bool fShutdown)
276 // Flush log data to the actual data file
277 // on all files that are not in use
278 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
281 CRITICAL_BLOCK(cs_db)
283 map<string, int>::iterator mi = mapFileUseCount.begin();
284 while (mi != mapFileUseCount.end())
286 string strFile = (*mi).first;
287 int nRefCount = (*mi).second;
288 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
291 // Move log data to the dat file
293 dbenv.txn_checkpoint(0, 0, 0);
294 printf("%s flush\n", strFile.c_str());
295 dbenv.lsn_reset(strFile.c_str(), 0);
296 mapFileUseCount.erase(mi++);
304 if (mapFileUseCount.empty())
306 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
322 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
326 return Read(make_pair(string("tx"), hash), txindex);
329 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
332 return Write(make_pair(string("tx"), hash), txindex);
335 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
340 uint256 hash = tx.GetHash();
341 CTxIndex txindex(pos, tx.vout.size());
342 return Write(make_pair(string("tx"), hash), txindex);
345 bool CTxDB::EraseTxIndex(const CTransaction& tx)
348 uint256 hash = tx.GetHash();
350 return Erase(make_pair(string("tx"), hash));
353 bool CTxDB::ContainsTx(uint256 hash)
356 return Exists(make_pair(string("tx"), hash));
359 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
365 Dbc* pcursor = GetCursor();
369 unsigned int fFlags = DB_SET_RANGE;
374 if (fFlags == DB_SET_RANGE)
375 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
377 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
379 if (ret == DB_NOTFOUND)
391 ssKey >> strType >> hashItem >> pos;
393 ssValue >> nItemHeight;
396 if (strType != "owner" || hashItem != hash160)
398 if (nItemHeight >= nMinHeight)
400 vtx.resize(vtx.size()+1);
401 if (!vtx.back().ReadFromDisk(pos))
413 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
417 if (!ReadTxIndex(hash, txindex))
419 return (tx.ReadFromDisk(txindex.pos));
422 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
425 return ReadDiskTx(hash, tx, txindex);
428 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
430 return ReadDiskTx(outpoint.hash, tx, txindex);
433 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
436 return ReadDiskTx(outpoint.hash, tx, txindex);
439 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
441 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
444 bool CTxDB::EraseBlockIndex(uint256 hash)
446 return Erase(make_pair(string("blockindex"), hash));
449 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
451 return Read(string("hashBestChain"), hashBestChain);
454 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
456 return Write(string("hashBestChain"), hashBestChain);
459 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
461 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
464 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
466 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
469 CBlockIndex static * InsertBlockIndex(uint256 hash)
475 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
476 if (mi != mapBlockIndex.end())
480 CBlockIndex* pindexNew = new CBlockIndex();
482 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
483 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
484 pindexNew->phashBlock = &((*mi).first);
489 bool CTxDB::LoadBlockIndex()
491 // Get database cursor
492 Dbc* pcursor = GetCursor();
496 // Load mapBlockIndex
497 unsigned int fFlags = DB_SET_RANGE;
502 if (fFlags == DB_SET_RANGE)
503 ssKey << make_pair(string("blockindex"), uint256(0));
505 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
507 if (ret == DB_NOTFOUND)
515 if (strType == "blockindex")
517 CDiskBlockIndex diskindex;
518 ssValue >> diskindex;
520 // Construct block index object
521 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
522 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
523 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
524 pindexNew->nFile = diskindex.nFile;
525 pindexNew->nBlockPos = diskindex.nBlockPos;
526 pindexNew->nHeight = diskindex.nHeight;
527 pindexNew->nVersion = diskindex.nVersion;
528 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
529 pindexNew->nTime = diskindex.nTime;
530 pindexNew->nBits = diskindex.nBits;
531 pindexNew->nNonce = diskindex.nNonce;
533 // Watch for genesis block
534 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
535 pindexGenesisBlock = pindexNew;
537 if (!pindexNew->CheckIndex())
538 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
547 // Calculate bnChainWork
548 vector<pair<int, CBlockIndex*> > vSortedByHeight;
549 vSortedByHeight.reserve(mapBlockIndex.size());
550 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
552 CBlockIndex* pindex = item.second;
553 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
555 sort(vSortedByHeight.begin(), vSortedByHeight.end());
556 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
558 CBlockIndex* pindex = item.second;
559 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
562 // Load hashBestChain pointer to end of best chain
563 if (!ReadHashBestChain(hashBestChain))
565 if (pindexGenesisBlock == NULL)
567 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
569 if (!mapBlockIndex.count(hashBestChain))
570 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
571 pindexBest = mapBlockIndex[hashBestChain];
572 nBestHeight = pindexBest->nHeight;
573 bnBestChainWork = pindexBest->bnChainWork;
574 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
576 // Load bnBestInvalidWork, OK if it doesn't exist
577 ReadBestInvalidWork(bnBestInvalidWork);
579 // Verify blocks in the best chain
580 CBlockIndex* pindexFork = NULL;
581 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
583 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
586 if (!block.ReadFromDisk(pindex))
587 return error("LoadBlockIndex() : block.ReadFromDisk failed");
588 if (!block.CheckBlock())
590 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
591 pindexFork = pindex->pprev;
596 // Reorg back to the fork
597 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
599 if (!block.ReadFromDisk(pindexFork))
600 return error("LoadBlockIndex() : block.ReadFromDisk failed");
602 block.SetBestChain(txdb, pindexFork);
616 bool CAddrDB::WriteAddress(const CAddress& addr)
618 return Write(make_pair(string("addr"), addr.GetKey()), addr);
621 bool CAddrDB::EraseAddress(const CAddress& addr)
623 return Erase(make_pair(string("addr"), addr.GetKey()));
626 bool CAddrDB::LoadAddresses()
628 CRITICAL_BLOCK(cs_mapAddresses)
630 // Load user provided addresses
631 CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
637 while (fgets(psz, sizeof(psz), filein))
639 CAddress addr(psz, false, NODE_NETWORK);
640 addr.nTime = 0; // so it won't relay unless successfully connected
649 Dbc* pcursor = GetCursor();
658 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
659 if (ret == DB_NOTFOUND)
667 if (strType == "addr")
671 mapAddresses.insert(make_pair(addr.GetKey(), addr));
676 printf("Loaded %d addresses\n", mapAddresses.size());
684 return CAddrDB("cr+").LoadAddresses();
694 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
697 return Write(make_pair(string("name"), strAddress), strName);
700 bool CWalletDB::EraseName(const string& strAddress)
702 // This should only be used for sending addresses, never for receiving addresses,
703 // receiving addresses must always have an address book entry if they're not change return.
705 return Erase(make_pair(string("name"), strAddress));
708 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
711 return Read(make_pair(string("acc"), strAccount), account);
714 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
716 return Write(make_pair(string("acc"), strAccount), account);
719 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
721 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
724 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
726 list<CAccountingEntry> entries;
727 ListAccountCreditDebit(strAccount, entries);
729 int64 nCreditDebit = 0;
730 BOOST_FOREACH (const CAccountingEntry& entry, entries)
731 nCreditDebit += entry.nCreditDebit;
736 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
738 bool fAllAccounts = (strAccount == "*");
740 Dbc* pcursor = GetCursor();
742 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
743 unsigned int fFlags = DB_SET_RANGE;
748 if (fFlags == DB_SET_RANGE)
749 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
751 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
753 if (ret == DB_NOTFOUND)
758 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
764 if (strType != "acentry")
766 CAccountingEntry acentry;
767 ssKey >> acentry.strAccount;
768 if (!fAllAccounts && acentry.strAccount != strAccount)
772 entries.push_back(acentry);
779 int CWalletDB::LoadWallet(CWallet* pwallet)
781 pwallet->vchDefaultKey.clear();
782 int nFileVersion = 0;
783 vector<uint256> vWalletUpgrade;
784 bool fIsEncrypted = false;
788 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
789 fMinimizeToTray = false;
790 fMinimizeOnClose = false;
793 //// todo: shouldn't we catch exceptions and try to recover and continue?
794 CRITICAL_BLOCK(pwallet->cs_wallet)
797 Dbc* pcursor = GetCursor();
806 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
807 if (ret == DB_NOTFOUND)
813 // Taking advantage of the fact that pair serialization
814 // is just the two items serialized one after the other
817 if (strType == "name")
821 ssValue >> pwallet->mapAddressBook[strAddress];
823 else if (strType == "tx")
827 CWalletTx& wtx = pwallet->mapWallet[hash];
829 wtx.pwallet = pwallet;
831 if (wtx.GetHash() != hash)
832 printf("Error in wallet.dat, hash mismatch\n");
834 // Undo serialize changes in 31600
835 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
837 if (!ssValue.empty())
841 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
842 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
843 wtx.fTimeReceivedIsTxTime = fTmp;
847 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
848 wtx.fTimeReceivedIsTxTime = 0;
850 vWalletUpgrade.push_back(hash);
854 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
855 //printf(" %12I64d %s %s %s\n",
856 // wtx.vout[0].nValue,
857 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
858 // wtx.hashBlock.ToString().substr(0,20).c_str(),
859 // wtx.mapValue["message"].c_str());
861 else if (strType == "acentry")
867 if (nNumber > nAccountingEntryNumber)
868 nAccountingEntryNumber = nNumber;
870 else if (strType == "key" || strType == "wkey")
872 vector<unsigned char> vchPubKey;
875 if (strType == "key")
879 key.SetPrivKey(pkey);
885 key.SetPrivKey(wkey.vchPrivKey);
887 if (!pwallet->LoadKey(key))
890 else if (strType == "mkey")
894 CMasterKey kMasterKey;
895 ssValue >> kMasterKey;
896 if(pwallet->mapMasterKeys.count(nID) != 0)
898 pwallet->mapMasterKeys[nID] = kMasterKey;
899 if (pwallet->nMasterKeyMaxID < nID)
900 pwallet->nMasterKeyMaxID = nID;
902 else if (strType == "ckey")
904 vector<unsigned char> vchPubKey;
906 vector<unsigned char> vchPrivKey;
907 ssValue >> vchPrivKey;
908 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
912 else if (strType == "defaultkey")
914 ssValue >> pwallet->vchDefaultKey;
916 else if (strType == "pool")
920 pwallet->setKeyPool.insert(nIndex);
922 else if (strType == "version")
924 ssValue >> nFileVersion;
925 if (nFileVersion == 10300)
928 else if (strType == "setting")
935 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
937 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
938 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
939 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
940 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
941 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
942 if (strKey == "fUseProxy") ssValue >> fUseProxy;
943 if (strKey == "addrProxy") ssValue >> addrProxy;
944 if (fHaveUPnP && strKey == "fUseUPnP") ssValue >> fUseUPnP;
946 else if (strType == "minversion")
949 ssValue >> nMinVersion;
950 if (nMinVersion > VERSION)
957 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
958 WriteTx(hash, pwallet->mapWallet[hash]);
960 printf("nFileVersion = %d\n", nFileVersion);
961 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
962 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
963 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
964 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
965 printf("fUseProxy = %d\n", fUseProxy);
966 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
968 printf("fUseUPnP = %d\n", fUseUPnP);
971 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
972 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
973 return DB_NEED_REWRITE;
975 if (nFileVersion < VERSION) // Update
977 // Get rid of old debug.log file in current directory
978 if (nFileVersion <= 105 && !pszSetDataDir[0])
981 WriteVersion(VERSION);
987 void ThreadFlushWalletDB(void* parg)
989 const string& strFile = ((const string*)parg)[0];
990 static bool fOneThread;
994 if (mapArgs.count("-noflushwallet"))
997 unsigned int nLastSeen = nWalletDBUpdated;
998 unsigned int nLastFlushed = nWalletDBUpdated;
999 int64 nLastWalletUpdate = GetTime();
1004 if (nLastSeen != nWalletDBUpdated)
1006 nLastSeen = nWalletDBUpdated;
1007 nLastWalletUpdate = GetTime();
1010 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1012 TRY_CRITICAL_BLOCK(cs_db)
1014 // Don't do this if any databases are in use
1016 map<string, int>::iterator mi = mapFileUseCount.begin();
1017 while (mi != mapFileUseCount.end())
1019 nRefCount += (*mi).second;
1023 if (nRefCount == 0 && !fShutdown)
1025 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1026 if (mi != mapFileUseCount.end())
1028 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1029 printf("Flushing wallet.dat\n");
1030 nLastFlushed = nWalletDBUpdated;
1031 int64 nStart = GetTimeMillis();
1033 // Flush wallet.dat so it's self contained
1035 dbenv.txn_checkpoint(0, 0, 0);
1036 dbenv.lsn_reset(strFile.c_str(), 0);
1038 mapFileUseCount.erase(mi++);
1039 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1047 bool BackupWallet(const CWallet& wallet, const string& strDest)
1049 if (!wallet.fFileBacked)
1053 CRITICAL_BLOCK(cs_db)
1055 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1057 // Flush log data to the dat file
1058 CloseDb(wallet.strWalletFile);
1059 dbenv.txn_checkpoint(0, 0, 0);
1060 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1061 mapFileUseCount.erase(wallet.strWalletFile);
1064 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1065 filesystem::path pathDest(strDest);
1066 if (filesystem::is_directory(pathDest))
1067 pathDest = pathDest / wallet.strWalletFile;
1068 #if BOOST_VERSION >= 104000
1069 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1071 filesystem::copy_file(pathSrc, pathDest);
1073 printf("copied wallet.dat to %s\n", pathDest.string().c_str());