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 COPYING 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)
396 ssKey >> strType >> hashItem >> pos;
397 ssValue >> nItemHeight;
399 catch (std::exception &e) {
400 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
404 if (strType != "owner" || hashItem != hash160)
406 if (nItemHeight >= nMinHeight)
408 vtx.resize(vtx.size()+1);
409 if (!vtx.back().ReadFromDisk(pos))
421 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
425 if (!ReadTxIndex(hash, txindex))
427 return (tx.ReadFromDisk(txindex.pos));
430 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
433 return ReadDiskTx(hash, tx, txindex);
436 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
438 return ReadDiskTx(outpoint.hash, tx, txindex);
441 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
444 return ReadDiskTx(outpoint.hash, tx, txindex);
447 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
449 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
452 bool CTxDB::EraseBlockIndex(uint256 hash)
454 return Erase(make_pair(string("blockindex"), hash));
457 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
459 return Read(string("hashBestChain"), hashBestChain);
462 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
464 return Write(string("hashBestChain"), hashBestChain);
467 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
469 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
472 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
474 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
477 CBlockIndex static * InsertBlockIndex(uint256 hash)
483 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
484 if (mi != mapBlockIndex.end())
488 CBlockIndex* pindexNew = new CBlockIndex();
490 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
491 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
492 pindexNew->phashBlock = &((*mi).first);
497 bool CTxDB::LoadBlockIndex()
499 // Get database cursor
500 Dbc* pcursor = GetCursor();
504 // Load mapBlockIndex
505 unsigned int fFlags = DB_SET_RANGE;
510 if (fFlags == DB_SET_RANGE)
511 ssKey << make_pair(string("blockindex"), uint256(0));
513 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
515 if (ret == DB_NOTFOUND)
525 if (strType == "blockindex")
527 CDiskBlockIndex diskindex;
528 ssValue >> diskindex;
530 // Construct block index object
531 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
532 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
533 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
534 pindexNew->nFile = diskindex.nFile;
535 pindexNew->nBlockPos = diskindex.nBlockPos;
536 pindexNew->nHeight = diskindex.nHeight;
537 pindexNew->nVersion = diskindex.nVersion;
538 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
539 pindexNew->nTime = diskindex.nTime;
540 pindexNew->nBits = diskindex.nBits;
541 pindexNew->nNonce = diskindex.nNonce;
543 // Watch for genesis block
544 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
545 pindexGenesisBlock = pindexNew;
547 if (!pindexNew->CheckIndex())
548 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
555 catch (std::exception &e) {
556 return error("%s() : deserialize error", __PRETTY_FUNCTION__);
561 // Calculate bnChainWork
562 vector<pair<int, CBlockIndex*> > vSortedByHeight;
563 vSortedByHeight.reserve(mapBlockIndex.size());
564 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
566 CBlockIndex* pindex = item.second;
567 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
569 sort(vSortedByHeight.begin(), vSortedByHeight.end());
570 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
572 CBlockIndex* pindex = item.second;
573 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
576 // Load hashBestChain pointer to end of best chain
577 if (!ReadHashBestChain(hashBestChain))
579 if (pindexGenesisBlock == NULL)
581 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
583 if (!mapBlockIndex.count(hashBestChain))
584 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
585 pindexBest = mapBlockIndex[hashBestChain];
586 nBestHeight = pindexBest->nHeight;
587 bnBestChainWork = pindexBest->bnChainWork;
588 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
590 // Load bnBestInvalidWork, OK if it doesn't exist
591 ReadBestInvalidWork(bnBestInvalidWork);
593 // Verify blocks in the best chain
594 CBlockIndex* pindexFork = NULL;
595 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
597 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
600 if (!block.ReadFromDisk(pindex))
601 return error("LoadBlockIndex() : block.ReadFromDisk failed");
602 if (!block.CheckBlock())
604 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
605 pindexFork = pindex->pprev;
610 // Reorg back to the fork
611 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
613 if (!block.ReadFromDisk(pindexFork))
614 return error("LoadBlockIndex() : block.ReadFromDisk failed");
616 block.SetBestChain(txdb, pindexFork);
630 bool CAddrDB::WriteAddress(const CAddress& addr)
632 return Write(make_pair(string("addr"), addr.GetKey()), addr);
635 bool CAddrDB::EraseAddress(const CAddress& addr)
637 return Erase(make_pair(string("addr"), addr.GetKey()));
640 bool CAddrDB::LoadAddresses()
642 CRITICAL_BLOCK(cs_mapAddresses)
645 Dbc* pcursor = GetCursor();
654 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
655 if (ret == DB_NOTFOUND)
663 if (strType == "addr")
667 mapAddresses.insert(make_pair(addr.GetKey(), addr));
672 printf("Loaded %d addresses\n", mapAddresses.size());
680 return CAddrDB("cr+").LoadAddresses();
690 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
693 return Write(make_pair(string("name"), strAddress), strName);
696 bool CWalletDB::EraseName(const string& strAddress)
698 // This should only be used for sending addresses, never for receiving addresses,
699 // receiving addresses must always have an address book entry if they're not change return.
701 return Erase(make_pair(string("name"), strAddress));
704 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
707 return Read(make_pair(string("acc"), strAccount), account);
710 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
712 return Write(make_pair(string("acc"), strAccount), account);
715 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
717 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
720 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
722 list<CAccountingEntry> entries;
723 ListAccountCreditDebit(strAccount, entries);
725 int64 nCreditDebit = 0;
726 BOOST_FOREACH (const CAccountingEntry& entry, entries)
727 nCreditDebit += entry.nCreditDebit;
732 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
734 bool fAllAccounts = (strAccount == "*");
736 Dbc* pcursor = GetCursor();
738 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
739 unsigned int fFlags = DB_SET_RANGE;
744 if (fFlags == DB_SET_RANGE)
745 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
747 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
749 if (ret == DB_NOTFOUND)
754 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
760 if (strType != "acentry")
762 CAccountingEntry acentry;
763 ssKey >> acentry.strAccount;
764 if (!fAllAccounts && acentry.strAccount != strAccount)
768 entries.push_back(acentry);
775 int CWalletDB::LoadWallet(CWallet* pwallet)
777 pwallet->vchDefaultKey.clear();
778 int nFileVersion = 0;
779 vector<uint256> vWalletUpgrade;
780 bool fIsEncrypted = false;
784 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
785 fMinimizeToTray = false;
786 fMinimizeOnClose = false;
789 //// todo: shouldn't we catch exceptions and try to recover and continue?
790 CRITICAL_BLOCK(pwallet->cs_wallet)
793 if (Read((string)"minversion", nMinVersion))
795 if (nMinVersion > VERSION)
800 Dbc* pcursor = GetCursor();
803 printf("Error getting wallet database cursor\n");
812 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
813 if (ret == DB_NOTFOUND)
817 printf("Error reading next record from wallet database\n");
822 // Taking advantage of the fact that pair serialization
823 // is just the two items serialized one after the other
826 if (strType == "name")
830 ssValue >> pwallet->mapAddressBook[strAddress];
832 else if (strType == "tx")
836 CWalletTx& wtx = pwallet->mapWallet[hash];
838 wtx.pwallet = pwallet;
840 if (wtx.GetHash() != hash)
841 printf("Error in wallet.dat, hash mismatch\n");
843 // Undo serialize changes in 31600
844 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
846 if (!ssValue.empty())
850 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
851 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
852 wtx.fTimeReceivedIsTxTime = fTmp;
856 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
857 wtx.fTimeReceivedIsTxTime = 0;
859 vWalletUpgrade.push_back(hash);
863 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
864 //printf(" %12"PRI64d" %s %s %s\n",
865 // wtx.vout[0].nValue,
866 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
867 // wtx.hashBlock.ToString().substr(0,20).c_str(),
868 // wtx.mapValue["message"].c_str());
870 else if (strType == "acentry")
876 if (nNumber > nAccountingEntryNumber)
877 nAccountingEntryNumber = nNumber;
879 else if (strType == "key" || strType == "wkey")
881 vector<unsigned char> vchPubKey;
884 if (strType == "key")
888 key.SetPrivKey(pkey);
889 if (key.GetPubKey() != vchPubKey)
891 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
896 printf("Error reading wallet database: invalid CPrivKey\n");
904 key.SetPrivKey(wkey.vchPrivKey);
905 if (key.GetPubKey() != vchPubKey)
907 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
912 printf("Error reading wallet database: invalid CWalletKey\n");
916 if (!pwallet->LoadKey(key))
918 printf("Error reading wallet database: LoadKey failed\n");
922 else if (strType == "mkey")
926 CMasterKey kMasterKey;
927 ssValue >> kMasterKey;
928 if(pwallet->mapMasterKeys.count(nID) != 0)
930 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
933 pwallet->mapMasterKeys[nID] = kMasterKey;
934 if (pwallet->nMasterKeyMaxID < nID)
935 pwallet->nMasterKeyMaxID = nID;
937 else if (strType == "ckey")
939 vector<unsigned char> vchPubKey;
941 vector<unsigned char> vchPrivKey;
942 ssValue >> vchPrivKey;
943 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
945 printf("Error reading wallet database: LoadCryptedKey failed\n");
950 else if (strType == "defaultkey")
952 ssValue >> pwallet->vchDefaultKey;
954 else if (strType == "pool")
958 pwallet->setKeyPool.insert(nIndex);
960 else if (strType == "version")
962 ssValue >> nFileVersion;
963 if (nFileVersion == 10300)
966 else if (strType == "setting")
973 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
975 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
976 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
977 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
978 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
979 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
980 if (strKey == "fUseProxy") ssValue >> fUseProxy;
981 if (strKey == "addrProxy") ssValue >> addrProxy;
982 if (fHaveUPnP && strKey == "fUseUPnP") ssValue >> fUseUPnP;
988 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
989 WriteTx(hash, pwallet->mapWallet[hash]);
991 printf("nFileVersion = %d\n", nFileVersion);
992 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
993 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
994 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
995 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
996 printf("fUseProxy = %d\n", fUseProxy);
997 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
999 printf("fUseUPnP = %d\n", fUseUPnP);
1002 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1003 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1004 return DB_NEED_REWRITE;
1006 if (nFileVersion < VERSION) // Update
1008 // Get rid of old debug.log file in current directory
1009 if (nFileVersion <= 105 && !pszSetDataDir[0])
1010 unlink("debug.log");
1012 WriteVersion(VERSION);
1018 void ThreadFlushWalletDB(void* parg)
1020 const string& strFile = ((const string*)parg)[0];
1021 static bool fOneThread;
1025 if (mapArgs.count("-noflushwallet"))
1028 unsigned int nLastSeen = nWalletDBUpdated;
1029 unsigned int nLastFlushed = nWalletDBUpdated;
1030 int64 nLastWalletUpdate = GetTime();
1035 if (nLastSeen != nWalletDBUpdated)
1037 nLastSeen = nWalletDBUpdated;
1038 nLastWalletUpdate = GetTime();
1041 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1043 TRY_CRITICAL_BLOCK(cs_db)
1045 // Don't do this if any databases are in use
1047 map<string, int>::iterator mi = mapFileUseCount.begin();
1048 while (mi != mapFileUseCount.end())
1050 nRefCount += (*mi).second;
1054 if (nRefCount == 0 && !fShutdown)
1056 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1057 if (mi != mapFileUseCount.end())
1059 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1060 printf("Flushing wallet.dat\n");
1061 nLastFlushed = nWalletDBUpdated;
1062 int64 nStart = GetTimeMillis();
1064 // Flush wallet.dat so it's self contained
1066 dbenv.txn_checkpoint(0, 0, 0);
1067 dbenv.lsn_reset(strFile.c_str(), 0);
1069 mapFileUseCount.erase(mi++);
1070 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1078 bool BackupWallet(const CWallet& wallet, const string& strDest)
1080 if (!wallet.fFileBacked)
1084 CRITICAL_BLOCK(cs_db)
1086 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1088 // Flush log data to the dat file
1089 CloseDb(wallet.strWalletFile);
1090 dbenv.txn_checkpoint(0, 0, 0);
1091 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1092 mapFileUseCount.erase(wallet.strWalletFile);
1095 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1096 filesystem::path pathDest(strDest);
1097 if (filesystem::is_directory(pathDest))
1098 pathDest = pathDest / wallet.strWalletFile;
1099 #if BOOST_VERSION >= 104000
1100 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1102 filesystem::copy_file(pathSrc, pathDest);
1104 printf("copied wallet.dat to %s\n", pathDest.string().c_str());