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)
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);
49 filesystem::path datadir(GetDataDir());
50 filesystem::directory_iterator it(datadir / "database");
51 while (it != filesystem::directory_iterator())
53 const filesystem::path& p = it->path();
54 #if BOOST_FILESYSTEM_VERSION >= 3
55 std::string f = p.filename().generic_string();
57 std::string f = p.filename();
59 if (f.find("log.") == 0)
60 filesystem::remove(p);
80 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
86 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
87 bool fCreate = strchr(pszMode, 'c');
88 unsigned int nFlags = DB_THREAD;
98 string strDataDir = GetDataDir();
99 string strLogDir = strDataDir + "/database";
100 filesystem::create_directory(strLogDir.c_str());
101 string strErrorFile = strDataDir + "/db.log";
102 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
104 dbenv.set_lg_dir(strLogDir.c_str());
105 dbenv.set_lg_max(10000000);
106 dbenv.set_lk_max_locks(10000);
107 dbenv.set_lk_max_objects(10000);
108 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
109 dbenv.set_flags(DB_AUTO_COMMIT, 1);
110 ret = dbenv.open(strDataDir.c_str(),
120 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
125 ++mapFileUseCount[strFile];
126 pdb = mapDb[strFile];
129 pdb = new Db(&dbenv, 0);
131 ret = pdb->open(NULL, // Txn pointer
133 "main", // Logical db name
134 DB_BTREE, // Database type
142 CRITICAL_BLOCK(cs_db)
143 --mapFileUseCount[strFile];
145 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
148 if (fCreate && !Exists(string("version")))
150 bool fTmp = fReadOnly;
152 WriteVersion(VERSION);
156 mapDb[strFile] = pdb;
166 vTxn.front()->abort();
170 // Flush database activity from memory pool to disk log
171 unsigned int nMinutes = 0;
174 if (strFile == "addr.dat")
176 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)
178 dbenv.txn_checkpoint(0, nMinutes, 0);
180 CRITICAL_BLOCK(cs_db)
181 --mapFileUseCount[strFile];
184 void static CloseDb(const string& strFile)
186 CRITICAL_BLOCK(cs_db)
188 if (mapDb[strFile] != NULL)
190 // Close the database handle
191 Db* pdb = mapDb[strFile];
194 mapDb[strFile] = NULL;
199 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
203 CRITICAL_BLOCK(cs_db)
205 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
207 // Flush log data to the dat file
209 dbenv.txn_checkpoint(0, 0, 0);
210 dbenv.lsn_reset(strFile.c_str(), 0);
211 mapFileUseCount.erase(strFile);
213 bool fSuccess = true;
214 printf("Rewriting %s...\n", strFile.c_str());
215 string strFileRes = strFile + ".rewrite";
216 CDB db(strFile.c_str(), "r");
217 Db* pdbCopy = new Db(&dbenv, 0);
219 int ret = pdbCopy->open(NULL, // Txn pointer
220 strFileRes.c_str(), // Filename
221 "main", // Logical db name
222 DB_BTREE, // Database type
227 printf("Cannot create database file %s\n", strFileRes.c_str());
231 Dbc* pcursor = db.GetCursor();
237 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
238 if (ret == DB_NOTFOUND)
250 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
252 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
258 Dbt datKey(&ssKey[0], ssKey.size());
259 Dbt datValue(&ssValue[0], ssValue.size());
260 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
268 if (pdbCopy->close(0))
275 if (dbA.remove(strFile.c_str(), NULL, 0))
278 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
282 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
292 void DBFlush(bool fShutdown, bool fRemoveLogFiles)
294 // Flush log data to the actual data file
295 // on all files that are not in use
296 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
299 CRITICAL_BLOCK(cs_db)
301 map<string, int>::iterator mi = mapFileUseCount.begin();
302 while (mi != mapFileUseCount.end())
304 string strFile = (*mi).first;
305 int nRefCount = (*mi).second;
306 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
309 // Move log data to the dat file
311 dbenv.txn_checkpoint(0, 0, 0);
312 printf("%s flush\n", strFile.c_str());
313 dbenv.lsn_reset(strFile.c_str(), 0);
314 mapFileUseCount.erase(mi++);
322 if (mapFileUseCount.empty())
324 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
325 EnvShutdown(fRemoveLogFiles);
340 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
344 return Read(make_pair(string("tx"), hash), txindex);
347 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
350 return Write(make_pair(string("tx"), hash), txindex);
353 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
358 uint256 hash = tx.GetHash();
359 CTxIndex txindex(pos, tx.vout.size());
360 return Write(make_pair(string("tx"), hash), txindex);
363 bool CTxDB::EraseTxIndex(const CTransaction& tx)
366 uint256 hash = tx.GetHash();
368 return Erase(make_pair(string("tx"), hash));
371 bool CTxDB::ContainsTx(uint256 hash)
374 return Exists(make_pair(string("tx"), hash));
377 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
383 Dbc* pcursor = GetCursor();
387 unsigned int fFlags = DB_SET_RANGE;
392 if (fFlags == DB_SET_RANGE)
393 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
395 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
397 if (ret == DB_NOTFOUND)
409 ssKey >> strType >> hashItem >> pos;
411 ssValue >> nItemHeight;
414 if (strType != "owner" || hashItem != hash160)
416 if (nItemHeight >= nMinHeight)
418 vtx.resize(vtx.size()+1);
419 if (!vtx.back().ReadFromDisk(pos))
431 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
435 if (!ReadTxIndex(hash, txindex))
437 return (tx.ReadFromDisk(txindex.pos));
440 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
443 return ReadDiskTx(hash, tx, txindex);
446 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
448 return ReadDiskTx(outpoint.hash, tx, txindex);
451 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
454 return ReadDiskTx(outpoint.hash, tx, txindex);
457 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
459 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
462 bool CTxDB::EraseBlockIndex(uint256 hash)
464 return Erase(make_pair(string("blockindex"), hash));
467 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
469 return Read(string("hashBestChain"), hashBestChain);
472 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
474 return Write(string("hashBestChain"), hashBestChain);
477 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
479 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
482 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
484 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
487 CBlockIndex static * InsertBlockIndex(uint256 hash)
493 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
494 if (mi != mapBlockIndex.end())
498 CBlockIndex* pindexNew = new CBlockIndex();
500 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
501 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
502 pindexNew->phashBlock = &((*mi).first);
507 bool CTxDB::LoadBlockIndex()
509 // Get database cursor
510 Dbc* pcursor = GetCursor();
514 // Load mapBlockIndex
515 unsigned int fFlags = DB_SET_RANGE;
520 if (fFlags == DB_SET_RANGE)
521 ssKey << make_pair(string("blockindex"), uint256(0));
523 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
525 if (ret == DB_NOTFOUND)
533 if (strType == "blockindex")
535 CDiskBlockIndex diskindex;
536 ssValue >> diskindex;
538 // Construct block index object
539 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
540 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
541 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
542 pindexNew->nFile = diskindex.nFile;
543 pindexNew->nBlockPos = diskindex.nBlockPos;
544 pindexNew->nHeight = diskindex.nHeight;
545 pindexNew->nVersion = diskindex.nVersion;
546 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
547 pindexNew->nTime = diskindex.nTime;
548 pindexNew->nBits = diskindex.nBits;
549 pindexNew->nNonce = diskindex.nNonce;
551 // Watch for genesis block
552 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
553 pindexGenesisBlock = pindexNew;
555 if (!pindexNew->CheckIndex())
556 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
565 // Calculate bnChainWork
566 vector<pair<int, CBlockIndex*> > vSortedByHeight;
567 vSortedByHeight.reserve(mapBlockIndex.size());
568 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
570 CBlockIndex* pindex = item.second;
571 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
573 sort(vSortedByHeight.begin(), vSortedByHeight.end());
574 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
576 CBlockIndex* pindex = item.second;
577 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
580 // Load hashBestChain pointer to end of best chain
581 if (!ReadHashBestChain(hashBestChain))
583 if (pindexGenesisBlock == NULL)
585 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
587 if (!mapBlockIndex.count(hashBestChain))
588 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
589 pindexBest = mapBlockIndex[hashBestChain];
590 nBestHeight = pindexBest->nHeight;
591 bnBestChainWork = pindexBest->bnChainWork;
592 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
594 // Load bnBestInvalidWork, OK if it doesn't exist
595 ReadBestInvalidWork(bnBestInvalidWork);
597 // Verify blocks in the best chain
598 CBlockIndex* pindexFork = NULL;
599 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
601 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
604 if (!block.ReadFromDisk(pindex))
605 return error("LoadBlockIndex() : block.ReadFromDisk failed");
606 if (!block.CheckBlock())
608 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
609 pindexFork = pindex->pprev;
614 // Reorg back to the fork
615 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
617 if (!block.ReadFromDisk(pindexFork))
618 return error("LoadBlockIndex() : block.ReadFromDisk failed");
620 block.SetBestChain(txdb, pindexFork);
634 bool CAddrDB::WriteAddress(const CAddress& addr)
636 return Write(make_pair(string("addr"), addr.GetKey()), addr);
639 bool CAddrDB::EraseAddress(const CAddress& addr)
641 return Erase(make_pair(string("addr"), addr.GetKey()));
644 bool CAddrDB::LoadAddresses()
646 CRITICAL_BLOCK(cs_mapAddresses)
648 // Load user provided addresses
649 CAutoFile filein = fopen((GetDataDir() + "/addr.txt").c_str(), "rt");
655 while (fgets(psz, sizeof(psz), filein))
657 CAddress addr(psz, false, NODE_NETWORK);
658 addr.nTime = 0; // so it won't relay unless successfully connected
667 Dbc* pcursor = GetCursor();
676 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
677 if (ret == DB_NOTFOUND)
685 if (strType == "addr")
689 mapAddresses.insert(make_pair(addr.GetKey(), addr));
694 printf("Loaded %d addresses\n", mapAddresses.size());
702 return CAddrDB("cr+").LoadAddresses();
712 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
715 return Write(make_pair(string("name"), strAddress), strName);
718 bool CWalletDB::EraseName(const string& strAddress)
720 // This should only be used for sending addresses, never for receiving addresses,
721 // receiving addresses must always have an address book entry if they're not change return.
723 return Erase(make_pair(string("name"), strAddress));
726 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
729 return Read(make_pair(string("acc"), strAccount), account);
732 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
734 return Write(make_pair(string("acc"), strAccount), account);
737 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
739 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
742 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
744 list<CAccountingEntry> entries;
745 ListAccountCreditDebit(strAccount, entries);
747 int64 nCreditDebit = 0;
748 BOOST_FOREACH (const CAccountingEntry& entry, entries)
749 nCreditDebit += entry.nCreditDebit;
754 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
756 bool fAllAccounts = (strAccount == "*");
758 Dbc* pcursor = GetCursor();
760 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
761 unsigned int fFlags = DB_SET_RANGE;
766 if (fFlags == DB_SET_RANGE)
767 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
769 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
771 if (ret == DB_NOTFOUND)
776 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
782 if (strType != "acentry")
784 CAccountingEntry acentry;
785 ssKey >> acentry.strAccount;
786 if (!fAllAccounts && acentry.strAccount != strAccount)
790 entries.push_back(acentry);
797 int CWalletDB::LoadWallet(CWallet* pwallet)
799 pwallet->vchDefaultKey.clear();
800 int nFileVersion = 0;
801 vector<uint256> vWalletUpgrade;
802 bool fIsEncrypted = false;
806 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
807 fMinimizeToTray = false;
808 fMinimizeOnClose = false;
811 //// todo: shouldn't we catch exceptions and try to recover and continue?
812 CRITICAL_BLOCK(pwallet->cs_wallet)
815 Dbc* pcursor = GetCursor();
824 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
825 if (ret == DB_NOTFOUND)
831 // Taking advantage of the fact that pair serialization
832 // is just the two items serialized one after the other
835 if (strType == "name")
839 ssValue >> pwallet->mapAddressBook[strAddress];
841 else if (strType == "tx")
845 CWalletTx& wtx = pwallet->mapWallet[hash];
847 wtx.pwallet = pwallet;
849 if (wtx.GetHash() != hash)
850 printf("Error in wallet.dat, hash mismatch\n");
852 // Undo serialize changes in 31600
853 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
855 if (!ssValue.empty())
859 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
860 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
861 wtx.fTimeReceivedIsTxTime = fTmp;
865 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
866 wtx.fTimeReceivedIsTxTime = 0;
868 vWalletUpgrade.push_back(hash);
872 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
873 //printf(" %12I64d %s %s %s\n",
874 // wtx.vout[0].nValue,
875 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
876 // wtx.hashBlock.ToString().substr(0,20).c_str(),
877 // wtx.mapValue["message"].c_str());
879 else if (strType == "acentry")
885 if (nNumber > nAccountingEntryNumber)
886 nAccountingEntryNumber = nNumber;
888 else if (strType == "key" || strType == "wkey")
890 vector<unsigned char> vchPubKey;
893 if (strType == "key")
897 key.SetPrivKey(pkey);
903 key.SetPrivKey(wkey.vchPrivKey);
905 if (!pwallet->LoadKey(key))
908 else if (strType == "mkey")
912 CMasterKey kMasterKey;
913 ssValue >> kMasterKey;
914 if(pwallet->mapMasterKeys.count(nID) != 0)
916 pwallet->mapMasterKeys[nID] = kMasterKey;
917 if (pwallet->nMasterKeyMaxID < nID)
918 pwallet->nMasterKeyMaxID = nID;
920 else if (strType == "ckey")
922 vector<unsigned char> vchPubKey;
924 vector<unsigned char> vchPrivKey;
925 ssValue >> vchPrivKey;
926 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
930 else if (strType == "defaultkey")
932 ssValue >> pwallet->vchDefaultKey;
934 else if (strType == "pool")
938 pwallet->setKeyPool.insert(nIndex);
940 else if (strType == "version")
942 ssValue >> nFileVersion;
943 if (nFileVersion == 10300)
946 else if (strType == "setting")
953 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
955 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
956 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
957 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
958 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
959 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
960 if (strKey == "fUseProxy") ssValue >> fUseProxy;
961 if (strKey == "addrProxy") ssValue >> addrProxy;
962 if (fHaveUPnP && strKey == "fUseUPnP") ssValue >> fUseUPnP;
964 else if (strType == "minversion")
967 ssValue >> nMinVersion;
968 if (nMinVersion > VERSION)
975 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
976 WriteTx(hash, pwallet->mapWallet[hash]);
978 printf("nFileVersion = %d\n", nFileVersion);
979 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
980 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
981 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
982 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
983 printf("fUseProxy = %d\n", fUseProxy);
984 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
986 printf("fUseUPnP = %d\n", fUseUPnP);
989 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
990 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
991 return DB_NEED_REWRITE;
993 if (nFileVersion < VERSION) // Update
995 // Get rid of old debug.log file in current directory
996 if (nFileVersion <= 105 && !pszSetDataDir[0])
999 WriteVersion(VERSION);
1005 void ThreadFlushWalletDB(void* parg)
1007 const string& strFile = ((const string*)parg)[0];
1008 static bool fOneThread;
1012 if (mapArgs.count("-noflushwallet"))
1015 unsigned int nLastSeen = nWalletDBUpdated;
1016 unsigned int nLastFlushed = nWalletDBUpdated;
1017 int64 nLastWalletUpdate = GetTime();
1022 if (nLastSeen != nWalletDBUpdated)
1024 nLastSeen = nWalletDBUpdated;
1025 nLastWalletUpdate = GetTime();
1028 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1030 TRY_CRITICAL_BLOCK(cs_db)
1032 // Don't do this if any databases are in use
1034 map<string, int>::iterator mi = mapFileUseCount.begin();
1035 while (mi != mapFileUseCount.end())
1037 nRefCount += (*mi).second;
1041 if (nRefCount == 0 && !fShutdown)
1043 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1044 if (mi != mapFileUseCount.end())
1046 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1047 printf("Flushing wallet.dat\n");
1048 nLastFlushed = nWalletDBUpdated;
1049 int64 nStart = GetTimeMillis();
1051 // Flush wallet.dat so it's self contained
1053 dbenv.txn_checkpoint(0, 0, 0);
1054 dbenv.lsn_reset(strFile.c_str(), 0);
1056 mapFileUseCount.erase(mi++);
1057 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1065 bool BackupWallet(const CWallet& wallet, const string& strDest)
1067 if (!wallet.fFileBacked)
1071 CRITICAL_BLOCK(cs_db)
1073 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1075 // Flush log data to the dat file
1076 CloseDb(wallet.strWalletFile);
1077 dbenv.txn_checkpoint(0, 0, 0);
1078 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1079 mapFileUseCount.erase(wallet.strWalletFile);
1082 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1083 filesystem::path pathDest(strDest);
1084 if (filesystem::is_directory(pathDest))
1085 pathDest = pathDest / wallet.strWalletFile;
1086 #if BOOST_VERSION >= 104000
1087 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1089 filesystem::copy_file(pathSrc, pathDest);
1091 printf("copied wallet.dat to %s\n", pathDest.string().c_str());