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 license.txt or http://www.opensource.org/licenses/mit-license.php.
9 #include <boost/version.hpp>
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
14 using namespace boost;
17 unsigned int nWalletDBUpdated;
18 uint64 nAccountingEntryNumber = 0;
26 static CCriticalSection cs_db;
27 static bool fDbEnvInit = false;
29 static map<string, int> mapFileUseCount;
30 static map<string, Db*> mapDb;
32 static void EnvShutdown()
42 catch (const DbException& e)
44 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
46 DbEnv(0).remove(GetDataDir().c_str(), 0);
63 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
69 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
70 bool fCreate = strchr(pszMode, 'c');
71 unsigned int nFlags = DB_THREAD;
81 string strDataDir = GetDataDir();
82 string strLogDir = strDataDir + "/database";
83 filesystem::create_directory(strLogDir.c_str());
84 string strErrorFile = strDataDir + "/db.log";
85 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
87 int nDbCache = GetArg("-dbcache", 25);
88 dbenv.set_lg_dir(strLogDir.c_str());
89 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
90 dbenv.set_lg_bsize(10485760);
91 dbenv.set_lg_max(104857600);
92 dbenv.set_lk_max_locks(10000);
93 dbenv.set_lk_max_objects(10000);
94 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
95 dbenv.set_flags(DB_AUTO_COMMIT, 1);
96 ret = dbenv.open(strDataDir.c_str(),
106 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
111 ++mapFileUseCount[strFile];
112 pdb = mapDb[strFile];
115 pdb = new Db(&dbenv, 0);
117 ret = pdb->open(NULL, // Txn pointer
119 "main", // Logical db name
120 DB_BTREE, // Database type
128 CRITICAL_BLOCK(cs_db)
129 --mapFileUseCount[strFile];
131 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
134 if (fCreate && !Exists(string("version")))
136 bool fTmp = fReadOnly;
138 WriteVersion(CLIENT_VERSION);
142 mapDb[strFile] = pdb;
152 vTxn.front()->abort();
156 // Flush database activity from memory pool to disk log
157 unsigned int nMinutes = 0;
160 if (strFile == "addr.dat")
162 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 5000 != 0)
164 dbenv.txn_checkpoint(0, nMinutes, 0);
166 CRITICAL_BLOCK(cs_db)
167 --mapFileUseCount[strFile];
170 void static CloseDb(const string& strFile)
172 CRITICAL_BLOCK(cs_db)
174 if (mapDb[strFile] != NULL)
176 // Close the database handle
177 Db* pdb = mapDb[strFile];
180 mapDb[strFile] = NULL;
185 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
189 CRITICAL_BLOCK(cs_db)
191 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
193 // Flush log data to the dat file
195 dbenv.txn_checkpoint(0, 0, 0);
196 dbenv.lsn_reset(strFile.c_str(), 0);
197 mapFileUseCount.erase(strFile);
199 bool fSuccess = true;
200 printf("Rewriting %s...\n", strFile.c_str());
201 string strFileRes = strFile + ".rewrite";
202 { // surround usage of db with extra {}
203 CDB db(strFile.c_str(), "r");
204 Db* pdbCopy = new Db(&dbenv, 0);
206 int ret = pdbCopy->open(NULL, // Txn pointer
207 strFileRes.c_str(), // Filename
208 "main", // Logical db name
209 DB_BTREE, // Database type
214 printf("Cannot create database file %s\n", strFileRes.c_str());
218 Dbc* pcursor = db.GetCursor();
224 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
225 if (ret == DB_NOTFOUND)
237 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
239 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
243 ssValue << CLIENT_VERSION;
245 Dbt datKey(&ssKey[0], ssKey.size());
246 Dbt datValue(&ssValue[0], ssValue.size());
247 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
255 if (pdbCopy->close(0))
263 if (dbA.remove(strFile.c_str(), NULL, 0))
266 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
270 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
280 void DBFlush(bool fShutdown)
282 // Flush log data to the actual data file
283 // on all files that are not in use
284 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
287 CRITICAL_BLOCK(cs_db)
289 map<string, int>::iterator mi = mapFileUseCount.begin();
290 while (mi != mapFileUseCount.end())
292 string strFile = (*mi).first;
293 int nRefCount = (*mi).second;
294 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
297 // Move log data to the dat file
299 dbenv.txn_checkpoint(0, 0, 0);
300 printf("%s flush\n", strFile.c_str());
301 dbenv.lsn_reset(strFile.c_str(), 0);
302 mapFileUseCount.erase(mi++);
310 if (mapFileUseCount.empty())
312 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
328 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
332 return Read(make_pair(string("tx"), hash), txindex);
335 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
338 return Write(make_pair(string("tx"), hash), txindex);
341 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
346 uint256 hash = tx.GetHash();
347 CTxIndex txindex(pos, tx.vout.size());
348 return Write(make_pair(string("tx"), hash), txindex);
351 bool CTxDB::EraseTxIndex(const CTransaction& tx)
354 uint256 hash = tx.GetHash();
356 return Erase(make_pair(string("tx"), hash));
359 bool CTxDB::ContainsTx(uint256 hash)
362 return Exists(make_pair(string("tx"), hash));
365 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
371 Dbc* pcursor = GetCursor();
375 unsigned int fFlags = DB_SET_RANGE;
380 if (fFlags == DB_SET_RANGE)
381 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
383 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
385 if (ret == DB_NOTFOUND)
397 ssKey >> strType >> hashItem >> pos;
399 ssValue >> nItemHeight;
402 if (strType != "owner" || hashItem != hash160)
404 if (nItemHeight >= nMinHeight)
406 vtx.resize(vtx.size()+1);
407 if (!vtx.back().ReadFromDisk(pos))
419 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
423 if (!ReadTxIndex(hash, txindex))
425 return (tx.ReadFromDisk(txindex.pos));
428 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
431 return ReadDiskTx(hash, tx, txindex);
434 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
436 return ReadDiskTx(outpoint.hash, tx, txindex);
439 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
442 return ReadDiskTx(outpoint.hash, tx, txindex);
445 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
447 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
450 bool CTxDB::EraseBlockIndex(uint256 hash)
452 return Erase(make_pair(string("blockindex"), hash));
455 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
457 return Read(string("hashBestChain"), hashBestChain);
460 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
462 return Write(string("hashBestChain"), hashBestChain);
465 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
467 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
470 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
472 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
475 CBlockIndex static * InsertBlockIndex(uint256 hash)
481 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
482 if (mi != mapBlockIndex.end())
486 CBlockIndex* pindexNew = new CBlockIndex();
488 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
489 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
490 pindexNew->phashBlock = &((*mi).first);
495 bool CTxDB::LoadBlockIndex()
497 // Get database cursor
498 Dbc* pcursor = GetCursor();
502 // Load mapBlockIndex
503 unsigned int fFlags = DB_SET_RANGE;
508 if (fFlags == DB_SET_RANGE)
509 ssKey << make_pair(string("blockindex"), uint256(0));
511 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
513 if (ret == DB_NOTFOUND)
521 if (strType == "blockindex")
523 CDiskBlockIndex diskindex;
524 ssValue >> diskindex;
526 // Construct block index object
527 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
528 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
529 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
530 pindexNew->nFile = diskindex.nFile;
531 pindexNew->nBlockPos = diskindex.nBlockPos;
532 pindexNew->nHeight = diskindex.nHeight;
533 pindexNew->nVersion = diskindex.nVersion;
534 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
535 pindexNew->nTime = diskindex.nTime;
536 pindexNew->nBits = diskindex.nBits;
537 pindexNew->nNonce = diskindex.nNonce;
539 // Watch for genesis block
540 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
541 pindexGenesisBlock = pindexNew;
543 if (!pindexNew->CheckIndex())
544 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
553 // Calculate bnChainWork
554 vector<pair<int, CBlockIndex*> > vSortedByHeight;
555 vSortedByHeight.reserve(mapBlockIndex.size());
556 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
558 CBlockIndex* pindex = item.second;
559 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
561 sort(vSortedByHeight.begin(), vSortedByHeight.end());
562 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
564 CBlockIndex* pindex = item.second;
565 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
568 // Load hashBestChain pointer to end of best chain
569 if (!ReadHashBestChain(hashBestChain))
571 if (pindexGenesisBlock == NULL)
573 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
575 if (!mapBlockIndex.count(hashBestChain))
576 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
577 pindexBest = mapBlockIndex[hashBestChain];
578 nBestHeight = pindexBest->nHeight;
579 bnBestChainWork = pindexBest->bnChainWork;
580 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
582 // Load bnBestInvalidWork, OK if it doesn't exist
583 ReadBestInvalidWork(bnBestInvalidWork);
585 // Verify blocks in the best chain
586 CBlockIndex* pindexFork = NULL;
587 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
589 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
592 if (!block.ReadFromDisk(pindex))
593 return error("LoadBlockIndex() : block.ReadFromDisk failed");
594 if (!block.CheckBlock())
596 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
597 pindexFork = pindex->pprev;
602 // Reorg back to the fork
603 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
605 if (!block.ReadFromDisk(pindexFork))
606 return error("LoadBlockIndex() : block.ReadFromDisk failed");
608 block.SetBestChain(txdb, pindexFork);
622 bool CAddrDB::WriteAddress(const CAddress& addr)
624 return Write(make_pair(string("addr"), addr.GetKey()), addr);
627 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
629 return Write(string("addrman"), addrman);
632 bool CAddrDB::EraseAddress(const CAddress& addr)
634 return Erase(make_pair(string("addr"), addr.GetKey()));
637 bool CAddrDB::LoadAddresses(bool &fUpdate)
639 bool fAddrMan = false;
640 if (Read(string("addrman"), addrman))
642 printf("Loaded %i addresses\n", addrman.size());
646 vector<CAddress> vAddr;
649 Dbc* pcursor = GetCursor();
658 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
659 if (ret == DB_NOTFOUND)
667 if (strType == "addr")
675 vAddr.push_back(addr);
684 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
685 printf("Loaded %i addresses\n", addrman.size());
693 bool fUpdate = false;
694 bool fRet = CAddrDB("cr+").LoadAddresses(fUpdate);
696 CDB::Rewrite("addr.dat", "\004addr");
707 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
710 return Write(make_pair(string("name"), strAddress), strName);
713 bool CWalletDB::EraseName(const string& strAddress)
715 // This should only be used for sending addresses, never for receiving addresses,
716 // receiving addresses must always have an address book entry if they're not change return.
718 return Erase(make_pair(string("name"), strAddress));
721 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
724 return Read(make_pair(string("acc"), strAccount), account);
727 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
729 return Write(make_pair(string("acc"), strAccount), account);
732 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
734 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
737 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
739 list<CAccountingEntry> entries;
740 ListAccountCreditDebit(strAccount, entries);
742 int64 nCreditDebit = 0;
743 BOOST_FOREACH (const CAccountingEntry& entry, entries)
744 nCreditDebit += entry.nCreditDebit;
749 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
751 bool fAllAccounts = (strAccount == "*");
753 Dbc* pcursor = GetCursor();
755 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
756 unsigned int fFlags = DB_SET_RANGE;
761 if (fFlags == DB_SET_RANGE)
762 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
764 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
766 if (ret == DB_NOTFOUND)
771 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
777 if (strType != "acentry")
779 CAccountingEntry acentry;
780 ssKey >> acentry.strAccount;
781 if (!fAllAccounts && acentry.strAccount != strAccount)
785 entries.push_back(acentry);
792 int CWalletDB::LoadWallet(CWallet* pwallet)
794 pwallet->vchDefaultKey.clear();
795 int nFileVersion = 0;
796 vector<uint256> vWalletUpgrade;
797 bool fIsEncrypted = false;
799 //// todo: shouldn't we catch exceptions and try to recover and continue?
800 CRITICAL_BLOCK(pwallet->cs_wallet)
803 Dbc* pcursor = GetCursor();
806 printf("Error getting wallet database cursor\n");
815 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
816 if (ret == DB_NOTFOUND)
820 printf("Error reading next record from wallet database\n");
825 // Taking advantage of the fact that pair serialization
826 // is just the two items serialized one after the other
829 if (strType == "name")
833 ssValue >> pwallet->mapAddressBook[strAddress];
835 else if (strType == "tx")
839 CWalletTx& wtx = pwallet->mapWallet[hash];
841 wtx.BindWallet(pwallet);
843 if (wtx.GetHash() != hash)
844 printf("Error in wallet.dat, hash mismatch\n");
846 // Undo serialize changes in 31600
847 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
849 if (!ssValue.empty())
853 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
854 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
855 wtx.fTimeReceivedIsTxTime = fTmp;
859 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
860 wtx.fTimeReceivedIsTxTime = 0;
862 vWalletUpgrade.push_back(hash);
866 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
867 //printf(" %12I64d %s %s %s\n",
868 // wtx.vout[0].nValue,
869 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
870 // wtx.hashBlock.ToString().substr(0,20).c_str(),
871 // wtx.mapValue["message"].c_str());
873 else if (strType == "acentry")
879 if (nNumber > nAccountingEntryNumber)
880 nAccountingEntryNumber = nNumber;
882 else if (strType == "key" || strType == "wkey")
884 vector<unsigned char> vchPubKey;
887 if (strType == "key")
891 key.SetPubKey(vchPubKey);
892 key.SetPrivKey(pkey);
893 if (key.GetPubKey() != vchPubKey)
895 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
900 printf("Error reading wallet database: invalid CPrivKey\n");
908 key.SetPubKey(vchPubKey);
909 key.SetPrivKey(wkey.vchPrivKey);
910 if (key.GetPubKey() != vchPubKey)
912 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
917 printf("Error reading wallet database: invalid CWalletKey\n");
921 if (!pwallet->LoadKey(key))
923 printf("Error reading wallet database: LoadKey failed\n");
927 else if (strType == "mkey")
931 CMasterKey kMasterKey;
932 ssValue >> kMasterKey;
933 if(pwallet->mapMasterKeys.count(nID) != 0)
935 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
938 pwallet->mapMasterKeys[nID] = kMasterKey;
939 if (pwallet->nMasterKeyMaxID < nID)
940 pwallet->nMasterKeyMaxID = nID;
942 else if (strType == "ckey")
944 vector<unsigned char> vchPubKey;
946 vector<unsigned char> vchPrivKey;
947 ssValue >> vchPrivKey;
948 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
950 printf("Error reading wallet database: LoadCryptedKey failed\n");
955 else if (strType == "defaultkey")
957 ssValue >> pwallet->vchDefaultKey;
959 else if (strType == "pool")
963 pwallet->setKeyPool.insert(nIndex);
965 else if (strType == "version")
967 ssValue >> nFileVersion;
968 if (nFileVersion == 10300)
971 else if (strType == "minversion")
974 ssValue >> nMinVersion;
975 if (nMinVersion > CLIENT_VERSION)
977 pwallet->LoadMinVersion(nMinVersion);
979 else if (strType == "cscript")
985 if (!pwallet->LoadCScript(script))
987 printf("Error reading wallet database: LoadCScript failed\n");
995 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
996 WriteTx(hash, pwallet->mapWallet[hash]);
998 printf("nFileVersion = %d\n", nFileVersion);
1001 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1002 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1003 return DB_NEED_REWRITE;
1005 if (nFileVersion < CLIENT_VERSION) // Update
1007 // Get rid of old debug.log file in current directory
1008 if (nFileVersion <= 105 && !pszSetDataDir[0])
1009 unlink("debug.log");
1011 WriteVersion(CLIENT_VERSION);
1017 void ThreadFlushWalletDB(void* parg)
1019 const string& strFile = ((const string*)parg)[0];
1020 static bool fOneThread;
1024 if (!GetBoolArg("-flushwallet", true))
1027 unsigned int nLastSeen = nWalletDBUpdated;
1028 unsigned int nLastFlushed = nWalletDBUpdated;
1029 int64 nLastWalletUpdate = GetTime();
1034 if (nLastSeen != nWalletDBUpdated)
1036 nLastSeen = nWalletDBUpdated;
1037 nLastWalletUpdate = GetTime();
1040 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1042 TRY_CRITICAL_BLOCK(cs_db)
1044 // Don't do this if any databases are in use
1046 map<string, int>::iterator mi = mapFileUseCount.begin();
1047 while (mi != mapFileUseCount.end())
1049 nRefCount += (*mi).second;
1053 if (nRefCount == 0 && !fShutdown)
1055 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1056 if (mi != mapFileUseCount.end())
1058 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1059 printf("Flushing wallet.dat\n");
1060 nLastFlushed = nWalletDBUpdated;
1061 int64 nStart = GetTimeMillis();
1063 // Flush wallet.dat so it's self contained
1065 dbenv.txn_checkpoint(0, 0, 0);
1066 dbenv.lsn_reset(strFile.c_str(), 0);
1068 mapFileUseCount.erase(mi++);
1069 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1077 bool BackupWallet(const CWallet& wallet, const string& strDest)
1079 if (!wallet.fFileBacked)
1083 CRITICAL_BLOCK(cs_db)
1085 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1087 // Flush log data to the dat file
1088 CloseDb(wallet.strWalletFile);
1089 dbenv.txn_checkpoint(0, 0, 0);
1090 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1091 mapFileUseCount.erase(wallet.strWalletFile);
1094 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1095 filesystem::path pathDest(strDest);
1096 if (filesystem::is_directory(pathDest))
1097 pathDest = pathDest / wallet.strWalletFile;
1100 #if BOOST_VERSION >= 104000
1101 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1103 filesystem::copy_file(pathSrc, pathDest);
1105 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1107 } catch(const filesystem::filesystem_error &e) {
1108 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());