1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
10 #include "checkpoints.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
15 using namespace boost;
18 unsigned int nWalletDBUpdated;
19 uint64 nAccountingEntryNumber = 0;
27 static CCriticalSection cs_db;
28 static bool fDbEnvInit = false;
30 static map<string, int> mapFileUseCount;
31 static map<string, Db*> mapDb;
33 static void EnvShutdown()
43 catch (const DbException& e)
45 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
47 DbEnv(0).remove(GetDataDir().c_str(), 0);
64 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
70 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
71 bool fCreate = strchr(pszMode, 'c');
72 unsigned int nFlags = DB_THREAD;
82 string strDataDir = GetDataDir();
83 string strLogDir = strDataDir + "/database";
84 filesystem::create_directory(strLogDir.c_str());
85 string strErrorFile = strDataDir + "/db.log";
86 printf("dbenv.open strLogDir=%s strErrorFile=%s\n", strLogDir.c_str(), strErrorFile.c_str());
88 dbenv.set_lg_dir(strLogDir.c_str());
89 dbenv.set_lg_max(10000000);
90 dbenv.set_lk_max_locks(10000);
91 dbenv.set_lk_max_objects(10000);
92 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
93 dbenv.set_flags(DB_AUTO_COMMIT, 1);
94 ret = dbenv.open(strDataDir.c_str(),
104 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
109 ++mapFileUseCount[strFile];
110 pdb = mapDb[strFile];
113 pdb = new Db(&dbenv, 0);
115 ret = pdb->open(NULL, // Txn pointer
117 "main", // Logical db name
118 DB_BTREE, // Database type
126 CRITICAL_BLOCK(cs_db)
127 --mapFileUseCount[strFile];
129 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
132 if (fCreate && !Exists(string("version")))
134 bool fTmp = fReadOnly;
136 WriteVersion(VERSION);
140 mapDb[strFile] = pdb;
150 vTxn.front()->abort();
154 // Flush database activity from memory pool to disk log
155 unsigned int nMinutes = 0;
158 if (strFile == "addr.dat")
160 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)
162 dbenv.txn_checkpoint(0, nMinutes, 0);
164 CRITICAL_BLOCK(cs_db)
165 --mapFileUseCount[strFile];
168 void static CloseDb(const string& strFile)
170 CRITICAL_BLOCK(cs_db)
172 if (mapDb[strFile] != NULL)
174 // Close the database handle
175 Db* pdb = mapDb[strFile];
178 mapDb[strFile] = NULL;
183 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
187 CRITICAL_BLOCK(cs_db)
189 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
191 // Flush log data to the dat file
193 dbenv.txn_checkpoint(0, 0, 0);
194 dbenv.lsn_reset(strFile.c_str(), 0);
195 mapFileUseCount.erase(strFile);
197 bool fSuccess = true;
198 printf("Rewriting %s...\n", strFile.c_str());
199 string strFileRes = strFile + ".rewrite";
200 { // surround usage of db with extra {}
201 CDB db(strFile.c_str(), "r");
202 Db* pdbCopy = new Db(&dbenv, 0);
204 int ret = pdbCopy->open(NULL, // Txn pointer
205 strFileRes.c_str(), // Filename
206 "main", // Logical db name
207 DB_BTREE, // Database type
212 printf("Cannot create database file %s\n", strFileRes.c_str());
216 Dbc* pcursor = db.GetCursor();
222 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
223 if (ret == DB_NOTFOUND)
235 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
237 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
243 Dbt datKey(&ssKey[0], ssKey.size());
244 Dbt datValue(&ssValue[0], ssValue.size());
245 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
253 if (pdbCopy->close(0))
261 if (dbA.remove(strFile.c_str(), NULL, 0))
264 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
268 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
278 void DBFlush(bool fShutdown)
280 // Flush log data to the actual data file
281 // on all files that are not in use
282 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
285 CRITICAL_BLOCK(cs_db)
287 map<string, int>::iterator mi = mapFileUseCount.begin();
288 while (mi != mapFileUseCount.end())
290 string strFile = (*mi).first;
291 int nRefCount = (*mi).second;
292 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
295 // Move log data to the dat file
297 dbenv.txn_checkpoint(0, 0, 0);
298 printf("%s flush\n", strFile.c_str());
299 dbenv.lsn_reset(strFile.c_str(), 0);
300 mapFileUseCount.erase(mi++);
308 if (mapFileUseCount.empty())
310 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
326 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
330 return Read(make_pair(string("tx"), hash), txindex);
333 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
336 return Write(make_pair(string("tx"), hash), txindex);
339 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
344 uint256 hash = tx.GetHash();
345 CTxIndex txindex(pos, tx.vout.size());
346 return Write(make_pair(string("tx"), hash), txindex);
349 bool CTxDB::EraseTxIndex(const CTransaction& tx)
352 uint256 hash = tx.GetHash();
354 return Erase(make_pair(string("tx"), hash));
357 bool CTxDB::ContainsTx(uint256 hash)
360 return Exists(make_pair(string("tx"), hash));
363 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
369 Dbc* pcursor = GetCursor();
373 unsigned int fFlags = DB_SET_RANGE;
378 if (fFlags == DB_SET_RANGE)
379 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
381 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
383 if (ret == DB_NOTFOUND)
395 ssKey >> strType >> hashItem >> pos;
397 ssValue >> nItemHeight;
400 if (strType != "owner" || hashItem != hash160)
402 if (nItemHeight >= nMinHeight)
404 vtx.resize(vtx.size()+1);
405 if (!vtx.back().ReadFromDisk(pos))
417 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
421 if (!ReadTxIndex(hash, txindex))
423 return (tx.ReadFromDisk(txindex.pos));
426 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
429 return ReadDiskTx(hash, tx, txindex);
432 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
434 return ReadDiskTx(outpoint.hash, tx, txindex);
437 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
440 return ReadDiskTx(outpoint.hash, tx, txindex);
443 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
445 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
448 bool CTxDB::EraseBlockIndex(uint256 hash)
450 return Erase(make_pair(string("blockindex"), hash));
453 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
455 return Read(string("hashBestChain"), hashBestChain);
458 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
460 return Write(string("hashBestChain"), hashBestChain);
463 bool CTxDB::ReadBestInvalidTrust(uint64& nBestInvalidTrust)
465 return Read(string("nBestInvalidTrust"), nBestInvalidTrust);
468 bool CTxDB::WriteBestInvalidTrust(uint64 nBestInvalidTrust)
470 return Write(string("nBestInvalidTrust"), nBestInvalidTrust);
473 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
475 return Read(string("hashSyncCheckpoint"), hashCheckpoint);
478 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
480 return Write(string("hashSyncCheckpoint"), hashCheckpoint);
483 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
485 return Read(string("strCheckpointPubKey"), strPubKey);
488 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
490 return Write(string("strCheckpointPubKey"), strPubKey);
493 CBlockIndex static * InsertBlockIndex(uint256 hash)
499 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
500 if (mi != mapBlockIndex.end())
504 CBlockIndex* pindexNew = new CBlockIndex();
506 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
507 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
508 pindexNew->phashBlock = &((*mi).first);
513 bool CTxDB::LoadBlockIndex()
515 // Get database cursor
516 Dbc* pcursor = GetCursor();
520 // Load mapBlockIndex
521 unsigned int fFlags = DB_SET_RANGE;
526 if (fFlags == DB_SET_RANGE)
527 ssKey << make_pair(string("blockindex"), uint256(0));
529 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
531 if (ret == DB_NOTFOUND)
539 if (strType == "blockindex")
541 CDiskBlockIndex diskindex;
542 ssValue >> diskindex;
544 // Construct block index object
545 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
546 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
547 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
548 pindexNew->nFile = diskindex.nFile;
549 pindexNew->nBlockPos = diskindex.nBlockPos;
550 pindexNew->nChainTrust = diskindex.nChainTrust;
551 pindexNew->nHeight = diskindex.nHeight;
552 pindexNew->fProofOfStake = diskindex.fProofOfStake;
553 pindexNew->prevoutStake = diskindex.prevoutStake;
554 pindexNew->nVersion = diskindex.nVersion;
555 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
556 pindexNew->nTime = diskindex.nTime;
557 pindexNew->nBits = diskindex.nBits;
558 pindexNew->nNonce = diskindex.nNonce;
560 // Watch for genesis block
561 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
562 pindexGenesisBlock = pindexNew;
564 if (!pindexNew->CheckIndex())
565 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
567 // ppcoin: build setStakeSeen
568 if (pindexNew->fProofOfStake)
569 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
578 // Load hashBestChain pointer to end of best chain
579 if (!ReadHashBestChain(hashBestChain))
581 if (pindexGenesisBlock == NULL)
583 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
585 if (!mapBlockIndex.count(hashBestChain))
586 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
587 pindexBest = mapBlockIndex[hashBestChain];
588 nBestHeight = pindexBest->nHeight;
589 nBestChainTrust = pindexBest->nChainTrust;
590 printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, nBestChainTrust);
592 // ppcoin: load hashSyncCheckpoint
593 if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
594 return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
595 printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
597 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
598 string strPubKey = "";
599 if (!ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
601 // write checkpoint master key to db
603 WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey);
605 return error("CTxDB::LoadBlockIndex() : failed to write new checkpoint master key");
606 if (!Checkpoints::ResetSyncCheckpoint())
607 return error("CTxDB::LoadBlockIndex() : failed to reset sync-checkpoint");
610 // Load nBestInvalidTrust, OK if it doesn't exist
611 ReadBestInvalidTrust(nBestInvalidTrust);
613 // Verify blocks in the best chain
614 CBlockIndex* pindexFork = NULL;
615 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
617 if (pindex->nHeight < nBestHeight-2500 && !mapArgs.count("-checkblocks"))
620 if (!block.ReadFromDisk(pindex))
621 return error("LoadBlockIndex() : block.ReadFromDisk failed");
622 if (!block.CheckBlock())
624 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
625 pindexFork = pindex->pprev;
630 // Reorg back to the fork
631 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
633 if (!block.ReadFromDisk(pindexFork))
634 return error("LoadBlockIndex() : block.ReadFromDisk failed");
636 block.SetBestChain(txdb, pindexFork);
650 bool CAddrDB::WriteAddress(const CAddress& addr)
652 return Write(make_pair(string("addr"), addr.GetKey()), addr);
655 bool CAddrDB::EraseAddress(const CAddress& addr)
657 return Erase(make_pair(string("addr"), addr.GetKey()));
660 bool CAddrDB::LoadAddresses()
662 CRITICAL_BLOCK(cs_mapAddresses)
665 Dbc* pcursor = GetCursor();
674 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
675 if (ret == DB_NOTFOUND)
683 if (strType == "addr")
687 mapAddresses.insert(make_pair(addr.GetKey(), addr));
692 printf("Loaded %d addresses\n", mapAddresses.size());
700 return CAddrDB("cr+").LoadAddresses();
710 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
713 return Write(make_pair(string("name"), strAddress), strName);
716 bool CWalletDB::EraseName(const string& strAddress)
718 // This should only be used for sending addresses, never for receiving addresses,
719 // receiving addresses must always have an address book entry if they're not change return.
721 return Erase(make_pair(string("name"), strAddress));
724 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
727 return Read(make_pair(string("acc"), strAccount), account);
730 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
732 return Write(make_pair(string("acc"), strAccount), account);
735 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
737 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
740 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
742 list<CAccountingEntry> entries;
743 ListAccountCreditDebit(strAccount, entries);
745 int64 nCreditDebit = 0;
746 BOOST_FOREACH (const CAccountingEntry& entry, entries)
747 nCreditDebit += entry.nCreditDebit;
752 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
754 bool fAllAccounts = (strAccount == "*");
756 Dbc* pcursor = GetCursor();
758 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
759 unsigned int fFlags = DB_SET_RANGE;
764 if (fFlags == DB_SET_RANGE)
765 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
767 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
769 if (ret == DB_NOTFOUND)
774 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
780 if (strType != "acentry")
782 CAccountingEntry acentry;
783 ssKey >> acentry.strAccount;
784 if (!fAllAccounts && acentry.strAccount != strAccount)
788 entries.push_back(acentry);
795 int CWalletDB::LoadWallet(CWallet* pwallet)
797 pwallet->vchDefaultKey.clear();
798 int nFileVersion = 0;
799 vector<uint256> vWalletUpgrade;
800 bool fIsEncrypted = false;
804 // Tray icon sometimes disappears on 9.10 karmic koala 64-bit, leaving no way to access the program
805 fMinimizeToTray = false;
806 fMinimizeOnClose = false;
809 //// todo: shouldn't we catch exceptions and try to recover and continue?
810 CRITICAL_BLOCK(pwallet->cs_wallet)
813 Dbc* pcursor = GetCursor();
822 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
823 if (ret == DB_NOTFOUND)
829 // Taking advantage of the fact that pair serialization
830 // is just the two items serialized one after the other
833 if (strType == "name")
837 ssValue >> pwallet->mapAddressBook[strAddress];
839 else if (strType == "tx")
843 CWalletTx& wtx = pwallet->mapWallet[hash];
845 wtx.pwallet = pwallet;
847 if (wtx.GetHash() != hash)
848 printf("Error in wallet.dat, hash mismatch\n");
850 // Undo serialize changes in 31600
851 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
853 if (!ssValue.empty())
857 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
858 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
859 wtx.fTimeReceivedIsTxTime = fTmp;
863 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
864 wtx.fTimeReceivedIsTxTime = 0;
866 vWalletUpgrade.push_back(hash);
870 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
871 //printf(" %12I64d %s %s %s\n",
872 // wtx.vout[0].nValue,
873 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
874 // wtx.hashBlock.ToString().substr(0,20).c_str(),
875 // wtx.mapValue["message"].c_str());
877 else if (strType == "acentry")
883 if (nNumber > nAccountingEntryNumber)
884 nAccountingEntryNumber = nNumber;
886 else if (strType == "key" || strType == "wkey")
888 vector<unsigned char> vchPubKey;
891 if (strType == "key")
895 key.SetPrivKey(pkey);
901 key.SetPrivKey(wkey.vchPrivKey);
903 if (!pwallet->LoadKey(key))
906 else if (strType == "mkey")
910 CMasterKey kMasterKey;
911 ssValue >> kMasterKey;
912 if(pwallet->mapMasterKeys.count(nID) != 0)
914 pwallet->mapMasterKeys[nID] = kMasterKey;
915 if (pwallet->nMasterKeyMaxID < nID)
916 pwallet->nMasterKeyMaxID = nID;
918 else if (strType == "ckey")
920 vector<unsigned char> vchPubKey;
922 vector<unsigned char> vchPrivKey;
923 ssValue >> vchPrivKey;
924 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
928 else if (strType == "defaultkey")
930 ssValue >> pwallet->vchDefaultKey;
932 else if (strType == "pool")
936 pwallet->setKeyPool.insert(nIndex);
938 else if (strType == "version")
940 ssValue >> nFileVersion;
941 if (nFileVersion == 10300)
944 else if (strType == "setting")
951 if (strKey == "fGenerateBitcoins") ssValue >> fGenerateBitcoins;
953 if (strKey == "nTransactionFee") ssValue >> nTransactionFee;
954 if (strKey == "fLimitProcessors") ssValue >> fLimitProcessors;
955 if (strKey == "nLimitProcessors") ssValue >> nLimitProcessors;
956 if (strKey == "fMinimizeToTray") ssValue >> fMinimizeToTray;
957 if (strKey == "fMinimizeOnClose") ssValue >> fMinimizeOnClose;
958 if (strKey == "fUseProxy") ssValue >> fUseProxy;
959 if (strKey == "addrProxy") ssValue >> addrProxy;
960 if (fHaveUPnP && strKey == "fUseUPnP") ssValue >> fUseUPnP;
961 if (strKey == "nBalanceReserve") ssValue >> nBalanceReserve;
963 else if (strType == "minversion")
966 ssValue >> nMinVersion;
967 if (nMinVersion > VERSION)
974 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
975 WriteTx(hash, pwallet->mapWallet[hash]);
977 printf("nFileVersion = %d\n", nFileVersion);
978 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
979 printf("nTransactionFee = %"PRI64d"\n", nTransactionFee);
980 printf("fMinimizeToTray = %d\n", fMinimizeToTray);
981 printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);
982 printf("fUseProxy = %d\n", fUseProxy);
983 printf("addrProxy = %s\n", addrProxy.ToString().c_str());
985 printf("fUseUPnP = %d\n", fUseUPnP);
988 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
989 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
990 return DB_NEED_REWRITE;
992 if (nFileVersion < VERSION) // Update
994 // Get rid of old debug.log file in current directory
995 if (nFileVersion <= 105 && !pszSetDataDir[0])
998 WriteVersion(VERSION);
1004 void ThreadFlushWalletDB(void* parg)
1006 const string& strFile = ((const string*)parg)[0];
1007 static bool fOneThread;
1011 if (mapArgs.count("-noflushwallet"))
1014 unsigned int nLastSeen = nWalletDBUpdated;
1015 unsigned int nLastFlushed = nWalletDBUpdated;
1016 int64 nLastWalletUpdate = GetTime();
1021 if (nLastSeen != nWalletDBUpdated)
1023 nLastSeen = nWalletDBUpdated;
1024 nLastWalletUpdate = GetTime();
1027 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1029 TRY_CRITICAL_BLOCK(cs_db)
1031 // Don't do this if any databases are in use
1033 map<string, int>::iterator mi = mapFileUseCount.begin();
1034 while (mi != mapFileUseCount.end())
1036 nRefCount += (*mi).second;
1040 if (nRefCount == 0 && !fShutdown)
1042 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1043 if (mi != mapFileUseCount.end())
1045 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1046 printf("Flushing wallet.dat\n");
1047 nLastFlushed = nWalletDBUpdated;
1048 int64 nStart = GetTimeMillis();
1050 // Flush wallet.dat so it's self contained
1052 dbenv.txn_checkpoint(0, 0, 0);
1053 dbenv.lsn_reset(strFile.c_str(), 0);
1055 mapFileUseCount.erase(mi++);
1056 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1064 bool BackupWallet(const CWallet& wallet, const string& strDest)
1066 if (!wallet.fFileBacked)
1070 CRITICAL_BLOCK(cs_db)
1072 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1074 // Flush log data to the dat file
1075 CloseDb(wallet.strWalletFile);
1076 dbenv.txn_checkpoint(0, 0, 0);
1077 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1078 mapFileUseCount.erase(wallet.strWalletFile);
1081 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1082 filesystem::path pathDest(strDest);
1083 if (filesystem::is_directory(pathDest))
1084 pathDest = pathDest / wallet.strWalletFile;
1085 #if BOOST_VERSION >= 104000
1086 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1088 filesystem::copy_file(pathSrc, pathDest);
1090 printf("copied wallet.dat to %s\n", pathDest.string().c_str());