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 bool fRemoveLogFiles = false;
32 void RemoveLogFilesOnShutdown(bool fIn)
34 fRemoveLogFiles = fIn;
36 static void EnvShutdown()
46 catch (const DbException& e)
48 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
50 DbEnv(0).remove(GetDataDir().c_str(), 0);
54 filesystem::path datadir(GetDataDir());
55 filesystem::directory_iterator it(datadir / "database");
56 while (it != filesystem::directory_iterator())
58 const filesystem::path& p = it->path();
59 #if BOOST_FILESYSTEM_VERSION >= 3
60 std::string f = p.filename().generic_string();
62 std::string f = p.filename();
64 if (f.find("log.") == 0)
65 filesystem::remove(p);
85 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
91 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
92 bool fCreate = strchr(pszMode, 'c');
93 unsigned int nFlags = DB_THREAD;
103 string strDataDir = GetDataDir();
104 string strLogDir = strDataDir + "/database";
105 filesystem::create_directory(strLogDir.c_str());
106 string strErrorFile = strDataDir + "/db.log";
107 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
109 dbenv.set_lg_dir(strLogDir.c_str());
110 dbenv.set_lg_max(10000000);
111 dbenv.set_lk_max_locks(10000);
112 dbenv.set_lk_max_objects(10000);
113 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
114 dbenv.set_flags(DB_AUTO_COMMIT, 1);
115 ret = dbenv.open(strDataDir.c_str(),
125 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
130 ++mapFileUseCount[strFile];
131 pdb = mapDb[strFile];
134 pdb = new Db(&dbenv, 0);
136 ret = pdb->open(NULL, // Txn pointer
138 "main", // Logical db name
139 DB_BTREE, // Database type
147 CRITICAL_BLOCK(cs_db)
148 --mapFileUseCount[strFile];
150 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
153 if (fCreate && !Exists(string("version")))
155 bool fTmp = fReadOnly;
157 WriteVersion(VERSION);
161 mapDb[strFile] = pdb;
171 vTxn.front()->abort();
175 // Flush database activity from memory pool to disk log
176 unsigned int nMinutes = 0;
179 if (strFile == "addr.dat")
181 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)
183 dbenv.txn_checkpoint(0, nMinutes, 0);
185 CRITICAL_BLOCK(cs_db)
186 --mapFileUseCount[strFile];
189 void static CloseDb(const string& strFile)
191 CRITICAL_BLOCK(cs_db)
193 if (mapDb[strFile] != NULL)
195 // Close the database handle
196 Db* pdb = mapDb[strFile];
199 mapDb[strFile] = NULL;
204 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
208 CRITICAL_BLOCK(cs_db)
210 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
212 // Flush log data to the dat file
214 dbenv.txn_checkpoint(0, 0, 0);
215 dbenv.lsn_reset(strFile.c_str(), 0);
216 mapFileUseCount.erase(strFile);
218 bool fSuccess = true;
219 printf("Rewriting %s...\n", strFile.c_str());
220 string strFileRes = strFile + ".rewrite";
221 CDB db(strFile.c_str(), "r");
222 Db* pdbCopy = new Db(&dbenv, 0);
224 int ret = pdbCopy->open(NULL, // Txn pointer
225 strFileRes.c_str(), // Filename
226 "main", // Logical db name
227 DB_BTREE, // Database type
232 printf("Cannot create database file %s\n", strFileRes.c_str());
236 Dbc* pcursor = db.GetCursor();
242 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
243 if (ret == DB_NOTFOUND)
255 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
257 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
263 Dbt datKey(&ssKey[0], ssKey.size());
264 Dbt datValue(&ssValue[0], ssValue.size());
265 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
273 if (pdbCopy->close(0))
280 if (dbA.remove(strFile.c_str(), NULL, 0))
283 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
287 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
297 void DBFlush(bool fShutdown)
299 // Flush log data to the actual data file
300 // on all files that are not in use
301 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
304 CRITICAL_BLOCK(cs_db)
306 map<string, int>::iterator mi = mapFileUseCount.begin();
307 while (mi != mapFileUseCount.end())
309 string strFile = (*mi).first;
310 int nRefCount = (*mi).second;
311 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
314 // Move log data to the dat file
316 dbenv.txn_checkpoint(0, 0, 0);
317 printf("%s flush\n", strFile.c_str());
318 dbenv.lsn_reset(strFile.c_str(), 0);
319 mapFileUseCount.erase(mi++);
327 if (mapFileUseCount.empty())
329 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
345 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
349 return Read(make_pair(string("tx"), hash), txindex);
352 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
355 return Write(make_pair(string("tx"), hash), txindex);
358 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
363 uint256 hash = tx.GetHash();
364 CTxIndex txindex(pos, tx.vout.size());
365 return Write(make_pair(string("tx"), hash), txindex);
368 bool CTxDB::EraseTxIndex(const CTransaction& tx)
371 uint256 hash = tx.GetHash();
373 return Erase(make_pair(string("tx"), hash));
376 bool CTxDB::ContainsTx(uint256 hash)
379 return Exists(make_pair(string("tx"), hash));
382 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
388 Dbc* pcursor = GetCursor();
392 unsigned int fFlags = DB_SET_RANGE;
397 if (fFlags == DB_SET_RANGE)
398 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
400 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
402 if (ret == DB_NOTFOUND)
414 ssKey >> strType >> hashItem >> pos;
416 ssValue >> nItemHeight;
419 if (strType != "owner" || hashItem != hash160)
421 if (nItemHeight >= nMinHeight)
423 vtx.resize(vtx.size()+1);
424 if (!vtx.back().ReadFromDisk(pos))
436 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
440 if (!ReadTxIndex(hash, txindex))
442 return (tx.ReadFromDisk(txindex.pos));
445 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
448 return ReadDiskTx(hash, tx, txindex);
451 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
453 return ReadDiskTx(outpoint.hash, tx, txindex);
456 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
459 return ReadDiskTx(outpoint.hash, tx, txindex);
462 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
464 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
467 bool CTxDB::EraseBlockIndex(uint256 hash)
469 return Erase(make_pair(string("blockindex"), hash));
472 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
474 return Read(string("hashBestChain"), hashBestChain);
477 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
479 return Write(string("hashBestChain"), hashBestChain);
482 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
484 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
487 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
489 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
492 CBlockIndex static * InsertBlockIndex(uint256 hash)
498 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
499 if (mi != mapBlockIndex.end())
503 CBlockIndex* pindexNew = new CBlockIndex();
505 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
506 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
507 pindexNew->phashBlock = &((*mi).first);
512 bool CTxDB::LoadBlockIndex()
514 // Get database cursor
515 Dbc* pcursor = GetCursor();
519 // Load mapBlockIndex
520 unsigned int fFlags = DB_SET_RANGE;
525 if (fFlags == DB_SET_RANGE)
526 ssKey << make_pair(string("blockindex"), uint256(0));
528 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
530 if (ret == DB_NOTFOUND)
538 if (strType == "blockindex")
540 CDiskBlockIndex diskindex;
541 ssValue >> diskindex;
543 // Construct block index object
544 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
545 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
546 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
547 pindexNew->nFile = diskindex.nFile;
548 pindexNew->nBlockPos = diskindex.nBlockPos;
549 pindexNew->nHeight = diskindex.nHeight;
550 pindexNew->nVersion = diskindex.nVersion;
551 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
552 pindexNew->nTime = diskindex.nTime;
553 pindexNew->nBits = diskindex.nBits;
554 pindexNew->nNonce = diskindex.nNonce;
556 // Watch for genesis block
557 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
558 pindexGenesisBlock = pindexNew;
560 if (!pindexNew->CheckIndex())
561 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
570 // Calculate bnChainWork
571 vector<pair<int, CBlockIndex*> > vSortedByHeight;
572 vSortedByHeight.reserve(mapBlockIndex.size());
573 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
575 CBlockIndex* pindex = item.second;
576 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
578 sort(vSortedByHeight.begin(), vSortedByHeight.end());
579 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
581 CBlockIndex* pindex = item.second;
582 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
585 // Load hashBestChain pointer to end of best chain
586 if (!ReadHashBestChain(hashBestChain))
588 if (pindexGenesisBlock == NULL)
590 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
592 if (!mapBlockIndex.count(hashBestChain))
593 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
594 pindexBest = mapBlockIndex[hashBestChain];
595 nBestHeight = pindexBest->nHeight;
596 bnBestChainWork = pindexBest->bnChainWork;
597 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
599 // Load bnBestInvalidWork, OK if it doesn't exist
600 ReadBestInvalidWork(bnBestInvalidWork);
602 // Verify blocks in the best chain
603 CBlockIndex* pindexFork = NULL;
604 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
606 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
609 if (!block.ReadFromDisk(pindex))
610 return error("LoadBlockIndex() : block.ReadFromDisk failed");
611 if (!block.CheckBlock())
613 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
614 pindexFork = pindex->pprev;
619 // Reorg back to the fork
620 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
622 if (!block.ReadFromDisk(pindexFork))
623 return error("LoadBlockIndex() : block.ReadFromDisk failed");
625 block.SetBestChain(txdb, pindexFork);
639 bool CAddrDB::WriteAddress(const CAddress& addr)
641 return Write(make_pair(string("addr"), addr.GetKey()), addr);
644 bool CAddrDB::EraseAddress(const CAddress& addr)
646 return Erase(make_pair(string("addr"), addr.GetKey()));
649 bool CAddrDB::LoadAddresses()
651 CRITICAL_BLOCK(cs_mapAddresses)
653 // Load user provided addresses
654 CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
660 while (fgets(psz, sizeof(psz), filein))
662 CAddress addr(psz, false, NODE_NETWORK);
663 addr.nTime = 0; // so it won't relay unless successfully connected
672 Dbc* pcursor = GetCursor();
681 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
682 if (ret == DB_NOTFOUND)
690 if (strType == "addr")
694 mapAddresses.insert(make_pair(addr.GetKey(), addr));
699 printf("Loaded %d addresses\n", mapAddresses.size());
707 return CAddrDB("cr+").LoadAddresses();
717 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
720 return Write(make_pair(string("name"), strAddress), strName);
723 bool CWalletDB::EraseName(const string& strAddress)
725 // This should only be used for sending addresses, never for receiving addresses,
726 // receiving addresses must always have an address book entry if they're not change return.
728 return Erase(make_pair(string("name"), strAddress));
731 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
734 return Read(make_pair(string("acc"), strAccount), account);
737 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
739 return Write(make_pair(string("acc"), strAccount), account);
742 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
744 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
747 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
749 list<CAccountingEntry> entries;
750 ListAccountCreditDebit(strAccount, entries);
752 int64 nCreditDebit = 0;
753 BOOST_FOREACH (const CAccountingEntry& entry, entries)
754 nCreditDebit += entry.nCreditDebit;
759 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
761 bool fAllAccounts = (strAccount == "*");
763 Dbc* pcursor = GetCursor();
765 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
766 unsigned int fFlags = DB_SET_RANGE;
771 if (fFlags == DB_SET_RANGE)
772 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
774 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
776 if (ret == DB_NOTFOUND)
781 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
787 if (strType != "acentry")
789 CAccountingEntry acentry;
790 ssKey >> acentry.strAccount;
791 if (!fAllAccounts && acentry.strAccount != strAccount)
795 entries.push_back(acentry);
802 int CWalletDB::LoadWallet(CWallet* pwallet)
804 pwallet->vchDefaultKey.clear();
805 int nFileVersion = 0;
806 vector<uint256> vWalletUpgrade;
807 bool fIsEncrypted = false;
811 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
812 fMinimizeToTray = false;
813 fMinimizeOnClose = false;
816 //// todo: shouldn't we catch exceptions and try to recover and continue?
817 CRITICAL_BLOCK(pwallet->cs_wallet)
820 Dbc* pcursor = GetCursor();
829 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
830 if (ret == DB_NOTFOUND)
836 // Taking advantage of the fact that pair serialization
837 // is just the two items serialized one after the other
840 if (strType == "name")
844 ssValue >> pwallet->mapAddressBook[strAddress];
846 else if (strType == "tx")
850 CWalletTx& wtx = pwallet->mapWallet[hash];
852 wtx.pwallet = pwallet;
854 if (wtx.GetHash() != hash)
855 printf("Error in wallet.dat, hash mismatch\n");
857 // Undo serialize changes in 31600
858 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
860 if (!ssValue.empty())
864 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
865 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
866 wtx.fTimeReceivedIsTxTime = fTmp;
870 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
871 wtx.fTimeReceivedIsTxTime = 0;
873 vWalletUpgrade.push_back(hash);
877 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
878 //printf(" %12I64d %s %s %s\n",
879 // wtx.vout[0].nValue,
880 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
881 // wtx.hashBlock.ToString().substr(0,20).c_str(),
882 // wtx.mapValue["message"].c_str());
884 else if (strType == "acentry")
890 if (nNumber > nAccountingEntryNumber)
891 nAccountingEntryNumber = nNumber;
893 else if (strType == "key" || strType == "wkey")
895 vector<unsigned char> vchPubKey;
898 if (strType == "key")
902 key.SetPrivKey(pkey);
908 key.SetPrivKey(wkey.vchPrivKey);
910 if (!pwallet->LoadKey(key))
913 else if (strType == "mkey")
917 CMasterKey kMasterKey;
918 ssValue >> kMasterKey;
919 if(pwallet->mapMasterKeys.count(nID) != 0)
921 pwallet->mapMasterKeys[nID] = kMasterKey;
922 if (pwallet->nMasterKeyMaxID < nID)
923 pwallet->nMasterKeyMaxID = nID;
925 else if (strType == "ckey")
927 vector<unsigned char> vchPubKey;
929 vector<unsigned char> vchPrivKey;
930 ssValue >> vchPrivKey;
931 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
935 else if (strType == "defaultkey")
937 ssValue >> pwallet->vchDefaultKey;
939 else if (strType == "pool")
943 pwallet->setKeyPool.insert(nIndex);
945 else if (strType == "version")
947 ssValue >> nFileVersion;
948 if (nFileVersion == 10300)
951 else if (strType == "setting")
958 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
960 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
961 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
962 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
963 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
964 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
965 if (strKey == "fUseProxy") ssValue >> fUseProxy;
966 if (strKey == "addrProxy") ssValue >> addrProxy;
967 if (fHaveUPnP && strKey == "fUseUPnP") ssValue >> fUseUPnP;
969 else if (strType == "minversion")
972 ssValue >> nMinVersion;
973 if (nMinVersion > VERSION)
980 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
981 WriteTx(hash, pwallet->mapWallet[hash]);
983 printf("nFileVersion = %d\n", nFileVersion);
984 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
985 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
986 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
987 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
988 printf("fUseProxy = %d\n", fUseProxy);
989 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
991 printf("fUseUPnP = %d\n", fUseUPnP);
994 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
995 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
996 return DB_NEED_REWRITE;
998 if (nFileVersion < VERSION) // Update
1000 // Get rid of old debug.log file in current directory
1001 if (nFileVersion <= 105 && !pszSetDataDir[0])
1002 unlink("debug.log");
1004 WriteVersion(VERSION);
1010 void ThreadFlushWalletDB(void* parg)
1012 const string& strFile = ((const string*)parg)[0];
1013 static bool fOneThread;
1017 if (mapArgs.count("-noflushwallet"))
1020 unsigned int nLastSeen = nWalletDBUpdated;
1021 unsigned int nLastFlushed = nWalletDBUpdated;
1022 int64 nLastWalletUpdate = GetTime();
1027 if (nLastSeen != nWalletDBUpdated)
1029 nLastSeen = nWalletDBUpdated;
1030 nLastWalletUpdate = GetTime();
1033 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1035 TRY_CRITICAL_BLOCK(cs_db)
1037 // Don't do this if any databases are in use
1039 map<string, int>::iterator mi = mapFileUseCount.begin();
1040 while (mi != mapFileUseCount.end())
1042 nRefCount += (*mi).second;
1046 if (nRefCount == 0 && !fShutdown)
1048 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1049 if (mi != mapFileUseCount.end())
1051 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1052 printf("Flushing wallet.dat\n");
1053 nLastFlushed = nWalletDBUpdated;
1054 int64 nStart = GetTimeMillis();
1056 // Flush wallet.dat so it's self contained
1058 dbenv.txn_checkpoint(0, 0, 0);
1059 dbenv.lsn_reset(strFile.c_str(), 0);
1061 mapFileUseCount.erase(mi++);
1062 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1070 bool BackupWallet(const CWallet& wallet, const string& strDest)
1072 if (!wallet.fFileBacked)
1076 CRITICAL_BLOCK(cs_db)
1078 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1080 // Flush log data to the dat file
1081 CloseDb(wallet.strWalletFile);
1082 dbenv.txn_checkpoint(0, 0, 0);
1083 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1084 mapFileUseCount.erase(wallet.strWalletFile);
1087 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1088 filesystem::path pathDest(strDest);
1089 if (filesystem::is_directory(pathDest))
1090 pathDest = pathDest / wallet.strWalletFile;
1091 #if BOOST_VERSION >= 104000
1092 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1094 filesystem::copy_file(pathSrc, pathDest);
1096 printf("copied wallet.dat to %s\n", pathDest.string().c_str());