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(1048576);
91 dbenv.set_lg_max(10485760);
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 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
97 ret = dbenv.open(strDataDir.c_str(),
107 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
112 ++mapFileUseCount[strFile];
113 pdb = mapDb[strFile];
116 pdb = new Db(&dbenv, 0);
118 ret = pdb->open(NULL, // Txn pointer
120 "main", // Logical db name
121 DB_BTREE, // Database type
129 CRITICAL_BLOCK(cs_db)
130 --mapFileUseCount[strFile];
132 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
135 if (fCreate && !Exists(string("version")))
137 bool fTmp = fReadOnly;
139 WriteVersion(CLIENT_VERSION);
143 mapDb[strFile] = pdb;
153 vTxn.front()->abort();
157 // Flush database activity from memory pool to disk log
158 unsigned int nMinutes = 0;
161 if (strFile == "addr.dat")
163 if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 5000 != 0)
165 dbenv.txn_checkpoint(0, nMinutes, 0);
167 CRITICAL_BLOCK(cs_db)
168 --mapFileUseCount[strFile];
171 void static CloseDb(const string& strFile)
173 CRITICAL_BLOCK(cs_db)
175 if (mapDb[strFile] != NULL)
177 // Close the database handle
178 Db* pdb = mapDb[strFile];
181 mapDb[strFile] = NULL;
186 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
190 CRITICAL_BLOCK(cs_db)
192 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
194 // Flush log data to the dat file
196 dbenv.txn_checkpoint(0, 0, 0);
197 dbenv.lsn_reset(strFile.c_str(), 0);
198 mapFileUseCount.erase(strFile);
200 bool fSuccess = true;
201 printf("Rewriting %s...\n", strFile.c_str());
202 string strFileRes = strFile + ".rewrite";
203 { // surround usage of db with extra {}
204 CDB db(strFile.c_str(), "r");
205 Db* pdbCopy = new Db(&dbenv, 0);
207 int ret = pdbCopy->open(NULL, // Txn pointer
208 strFileRes.c_str(), // Filename
209 "main", // Logical db name
210 DB_BTREE, // Database type
215 printf("Cannot create database file %s\n", strFileRes.c_str());
219 Dbc* pcursor = db.GetCursor();
225 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
226 if (ret == DB_NOTFOUND)
238 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
240 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
244 ssValue << CLIENT_VERSION;
246 Dbt datKey(&ssKey[0], ssKey.size());
247 Dbt datValue(&ssValue[0], ssValue.size());
248 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
256 if (pdbCopy->close(0))
264 if (dbA.remove(strFile.c_str(), NULL, 0))
267 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
271 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
281 void DBFlush(bool fShutdown)
283 // Flush log data to the actual data file
284 // on all files that are not in use
285 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
288 CRITICAL_BLOCK(cs_db)
290 map<string, int>::iterator mi = mapFileUseCount.begin();
291 while (mi != mapFileUseCount.end())
293 string strFile = (*mi).first;
294 int nRefCount = (*mi).second;
295 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
298 // Move log data to the dat file
300 dbenv.txn_checkpoint(0, 0, 0);
301 printf("%s flush\n", strFile.c_str());
302 dbenv.lsn_reset(strFile.c_str(), 0);
303 mapFileUseCount.erase(mi++);
311 if (mapFileUseCount.empty())
313 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
329 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
333 return Read(make_pair(string("tx"), hash), txindex);
336 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
339 return Write(make_pair(string("tx"), hash), txindex);
342 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
347 uint256 hash = tx.GetHash();
348 CTxIndex txindex(pos, tx.vout.size());
349 return Write(make_pair(string("tx"), hash), txindex);
352 bool CTxDB::EraseTxIndex(const CTransaction& tx)
355 uint256 hash = tx.GetHash();
357 return Erase(make_pair(string("tx"), hash));
360 bool CTxDB::ContainsTx(uint256 hash)
363 return Exists(make_pair(string("tx"), hash));
366 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
372 Dbc* pcursor = GetCursor();
376 unsigned int fFlags = DB_SET_RANGE;
381 if (fFlags == DB_SET_RANGE)
382 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
384 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
386 if (ret == DB_NOTFOUND)
398 ssKey >> strType >> hashItem >> pos;
400 ssValue >> nItemHeight;
403 if (strType != "owner" || hashItem != hash160)
405 if (nItemHeight >= nMinHeight)
407 vtx.resize(vtx.size()+1);
408 if (!vtx.back().ReadFromDisk(pos))
420 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
424 if (!ReadTxIndex(hash, txindex))
426 return (tx.ReadFromDisk(txindex.pos));
429 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
432 return ReadDiskTx(hash, tx, txindex);
435 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
437 return ReadDiskTx(outpoint.hash, tx, txindex);
440 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
443 return ReadDiskTx(outpoint.hash, tx, txindex);
446 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
448 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
451 bool CTxDB::EraseBlockIndex(uint256 hash)
453 return Erase(make_pair(string("blockindex"), hash));
456 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
458 return Read(string("hashBestChain"), hashBestChain);
461 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
463 return Write(string("hashBestChain"), hashBestChain);
466 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
468 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
471 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
473 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
476 CBlockIndex static * InsertBlockIndex(uint256 hash)
482 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
483 if (mi != mapBlockIndex.end())
487 CBlockIndex* pindexNew = new CBlockIndex();
489 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
490 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
491 pindexNew->phashBlock = &((*mi).first);
496 bool CTxDB::LoadBlockIndex()
498 // Get database cursor
499 Dbc* pcursor = GetCursor();
503 // Load mapBlockIndex
504 unsigned int fFlags = DB_SET_RANGE;
509 if (fFlags == DB_SET_RANGE)
510 ssKey << make_pair(string("blockindex"), uint256(0));
512 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
514 if (ret == DB_NOTFOUND)
522 if (strType == "blockindex")
524 CDiskBlockIndex diskindex;
525 ssValue >> diskindex;
527 // Construct block index object
528 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
529 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
530 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
531 pindexNew->nFile = diskindex.nFile;
532 pindexNew->nBlockPos = diskindex.nBlockPos;
533 pindexNew->nHeight = diskindex.nHeight;
534 pindexNew->nVersion = diskindex.nVersion;
535 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
536 pindexNew->nTime = diskindex.nTime;
537 pindexNew->nBits = diskindex.nBits;
538 pindexNew->nNonce = diskindex.nNonce;
540 // Watch for genesis block
541 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
542 pindexGenesisBlock = pindexNew;
544 if (!pindexNew->CheckIndex())
545 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
554 // Calculate bnChainWork
555 vector<pair<int, CBlockIndex*> > vSortedByHeight;
556 vSortedByHeight.reserve(mapBlockIndex.size());
557 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
559 CBlockIndex* pindex = item.second;
560 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
562 sort(vSortedByHeight.begin(), vSortedByHeight.end());
563 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
565 CBlockIndex* pindex = item.second;
566 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
569 // Load hashBestChain pointer to end of best chain
570 if (!ReadHashBestChain(hashBestChain))
572 if (pindexGenesisBlock == NULL)
574 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
576 if (!mapBlockIndex.count(hashBestChain))
577 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
578 pindexBest = mapBlockIndex[hashBestChain];
579 nBestHeight = pindexBest->nHeight;
580 bnBestChainWork = pindexBest->bnChainWork;
581 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
583 // Load bnBestInvalidWork, OK if it doesn't exist
584 ReadBestInvalidWork(bnBestInvalidWork);
586 // Verify blocks in the best chain
587 int nCheckLevel = GetArg("-checklevel", 1);
588 int nCheckDepth = GetArg( "-checkblocks", 2500);
589 if (nCheckDepth == 0)
590 nCheckDepth = 1000000000; // suffices until the year 19000
591 if (nCheckDepth > nBestHeight)
592 nCheckDepth = nBestHeight;
593 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
594 CBlockIndex* pindexFork = NULL;
595 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
596 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
598 if (pindex->nHeight < nBestHeight-nCheckDepth)
601 if (!block.ReadFromDisk(pindex))
602 return error("LoadBlockIndex() : block.ReadFromDisk failed");
603 // check level 1: verify block validity
604 if (nCheckLevel>0 && !block.CheckBlock())
606 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
607 pindexFork = pindex->pprev;
609 // check level 2: verify transaction index validity
612 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
613 mapBlockPos[pos] = pindex;
614 BOOST_FOREACH(const CTransaction &tx, block.vtx)
616 uint256 hashTx = tx.GetHash();
618 if (ReadTxIndex(hashTx, txindex))
620 // check level 3: checker transaction hashes
621 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
623 // either an error or a duplicate transaction
624 CTransaction txFound;
625 if (!txFound.ReadFromDisk(txindex.pos))
627 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
628 pindexFork = pindex->pprev;
631 if (txFound.GetHash() != hashTx) // not a duplicate tx
633 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
634 pindexFork = pindex->pprev;
637 // check level 4: check whether spent txouts were spent within the main chain
640 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
644 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
645 if (!mapBlockPos.count(posFind))
647 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
648 pindexFork = pindex->pprev;
650 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
653 CTransaction txSpend;
654 if (!txSpend.ReadFromDisk(txpos))
656 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
657 pindexFork = pindex->pprev;
659 else if (!txSpend.CheckTransaction())
661 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
662 pindexFork = pindex->pprev;
667 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
668 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
672 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
673 pindexFork = pindex->pprev;
681 // check level 5: check whether all prevouts are marked spent
683 BOOST_FOREACH(const CTxIn &txin, tx.vin)
686 if (ReadTxIndex(txin.prevout.hash, txindex))
687 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
689 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
690 pindexFork = pindex->pprev;
698 // Reorg back to the fork
699 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
701 if (!block.ReadFromDisk(pindexFork))
702 return error("LoadBlockIndex() : block.ReadFromDisk failed");
704 block.SetBestChain(txdb, pindexFork);
718 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
720 return Write(string("addrman"), addrman);
723 bool CAddrDB::LoadAddresses()
725 if (Read(string("addrman"), addrman))
727 printf("Loaded %i addresses\n", addrman.size());
731 // Read pre-0.6 addr records
733 vector<CAddress> vAddr;
734 vector<vector<unsigned char> > vDelete;
737 Dbc* pcursor = GetCursor();
746 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
747 if (ret == DB_NOTFOUND)
755 if (strType == "addr")
759 vAddr.push_back(addr);
764 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
765 printf("Loaded %i addresses\n", addrman.size());
767 // Note: old records left; we ran into hangs-on-startup
768 // bugs for some users who (we think) were running after
769 // an unclean shutdown.
776 return CAddrDB("cr+").LoadAddresses();
786 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
789 return Write(make_pair(string("name"), strAddress), strName);
792 bool CWalletDB::EraseName(const string& strAddress)
794 // This should only be used for sending addresses, never for receiving addresses,
795 // receiving addresses must always have an address book entry if they're not change return.
797 return Erase(make_pair(string("name"), strAddress));
800 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
803 return Read(make_pair(string("acc"), strAccount), account);
806 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
808 return Write(make_pair(string("acc"), strAccount), account);
811 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
813 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
816 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
818 list<CAccountingEntry> entries;
819 ListAccountCreditDebit(strAccount, entries);
821 int64 nCreditDebit = 0;
822 BOOST_FOREACH (const CAccountingEntry& entry, entries)
823 nCreditDebit += entry.nCreditDebit;
828 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
830 bool fAllAccounts = (strAccount == "*");
832 Dbc* pcursor = GetCursor();
834 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
835 unsigned int fFlags = DB_SET_RANGE;
840 if (fFlags == DB_SET_RANGE)
841 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
843 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
845 if (ret == DB_NOTFOUND)
850 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
856 if (strType != "acentry")
858 CAccountingEntry acentry;
859 ssKey >> acentry.strAccount;
860 if (!fAllAccounts && acentry.strAccount != strAccount)
864 entries.push_back(acentry);
871 int CWalletDB::LoadWallet(CWallet* pwallet)
873 pwallet->vchDefaultKey.clear();
874 int nFileVersion = 0;
875 vector<uint256> vWalletUpgrade;
876 bool fIsEncrypted = false;
878 //// todo: shouldn't we catch exceptions and try to recover and continue?
879 CRITICAL_BLOCK(pwallet->cs_wallet)
882 if (Read((string)"minversion", nMinVersion))
884 if (nMinVersion > CLIENT_VERSION)
886 pwallet->LoadMinVersion(nMinVersion);
890 Dbc* pcursor = GetCursor();
893 printf("Error getting wallet database cursor\n");
902 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
903 if (ret == DB_NOTFOUND)
907 printf("Error reading next record from wallet database\n");
912 // Taking advantage of the fact that pair serialization
913 // is just the two items serialized one after the other
916 if (strType == "name")
920 ssValue >> pwallet->mapAddressBook[strAddress];
922 else if (strType == "tx")
926 CWalletTx& wtx = pwallet->mapWallet[hash];
928 wtx.BindWallet(pwallet);
930 if (wtx.GetHash() != hash)
931 printf("Error in wallet.dat, hash mismatch\n");
933 // Undo serialize changes in 31600
934 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
936 if (!ssValue.empty())
940 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
941 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
942 wtx.fTimeReceivedIsTxTime = fTmp;
946 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
947 wtx.fTimeReceivedIsTxTime = 0;
949 vWalletUpgrade.push_back(hash);
953 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
954 //printf(" %12I64d %s %s %s\n",
955 // wtx.vout[0].nValue,
956 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
957 // wtx.hashBlock.ToString().substr(0,20).c_str(),
958 // wtx.mapValue["message"].c_str());
960 else if (strType == "acentry")
966 if (nNumber > nAccountingEntryNumber)
967 nAccountingEntryNumber = nNumber;
969 else if (strType == "key" || strType == "wkey")
971 vector<unsigned char> vchPubKey;
974 if (strType == "key")
978 key.SetPubKey(vchPubKey);
979 key.SetPrivKey(pkey);
980 if (key.GetPubKey() != vchPubKey)
982 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
987 printf("Error reading wallet database: invalid CPrivKey\n");
995 key.SetPubKey(vchPubKey);
996 key.SetPrivKey(wkey.vchPrivKey);
997 if (key.GetPubKey() != vchPubKey)
999 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1004 printf("Error reading wallet database: invalid CWalletKey\n");
1008 if (!pwallet->LoadKey(key))
1010 printf("Error reading wallet database: LoadKey failed\n");
1014 else if (strType == "mkey")
1018 CMasterKey kMasterKey;
1019 ssValue >> kMasterKey;
1020 if(pwallet->mapMasterKeys.count(nID) != 0)
1022 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1025 pwallet->mapMasterKeys[nID] = kMasterKey;
1026 if (pwallet->nMasterKeyMaxID < nID)
1027 pwallet->nMasterKeyMaxID = nID;
1029 else if (strType == "ckey")
1031 vector<unsigned char> vchPubKey;
1033 vector<unsigned char> vchPrivKey;
1034 ssValue >> vchPrivKey;
1035 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1037 printf("Error reading wallet database: LoadCryptedKey failed\n");
1040 fIsEncrypted = true;
1042 else if (strType == "defaultkey")
1044 ssValue >> pwallet->vchDefaultKey;
1046 else if (strType == "pool")
1050 pwallet->setKeyPool.insert(nIndex);
1052 else if (strType == "version")
1054 ssValue >> nFileVersion;
1055 if (nFileVersion == 10300)
1058 else if (strType == "cscript")
1064 if (!pwallet->LoadCScript(script))
1066 printf("Error reading wallet database: LoadCScript failed\n");
1074 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1075 WriteTx(hash, pwallet->mapWallet[hash]);
1077 printf("nFileVersion = %d\n", nFileVersion);
1080 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1081 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1082 return DB_NEED_REWRITE;
1084 if (nFileVersion < CLIENT_VERSION) // Update
1086 // Get rid of old debug.log file in current directory
1087 if (nFileVersion <= 105 && !pszSetDataDir[0])
1088 unlink("debug.log");
1090 WriteVersion(CLIENT_VERSION);
1096 void ThreadFlushWalletDB(void* parg)
1098 const string& strFile = ((const string*)parg)[0];
1099 static bool fOneThread;
1103 if (!GetBoolArg("-flushwallet", true))
1106 unsigned int nLastSeen = nWalletDBUpdated;
1107 unsigned int nLastFlushed = nWalletDBUpdated;
1108 int64 nLastWalletUpdate = GetTime();
1113 if (nLastSeen != nWalletDBUpdated)
1115 nLastSeen = nWalletDBUpdated;
1116 nLastWalletUpdate = GetTime();
1119 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1121 TRY_CRITICAL_BLOCK(cs_db)
1123 // Don't do this if any databases are in use
1125 map<string, int>::iterator mi = mapFileUseCount.begin();
1126 while (mi != mapFileUseCount.end())
1128 nRefCount += (*mi).second;
1132 if (nRefCount == 0 && !fShutdown)
1134 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1135 if (mi != mapFileUseCount.end())
1137 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1138 printf("Flushing wallet.dat\n");
1139 nLastFlushed = nWalletDBUpdated;
1140 int64 nStart = GetTimeMillis();
1142 // Flush wallet.dat so it's self contained
1144 dbenv.txn_checkpoint(0, 0, 0);
1145 dbenv.lsn_reset(strFile.c_str(), 0);
1147 mapFileUseCount.erase(mi++);
1148 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1156 bool BackupWallet(const CWallet& wallet, const string& strDest)
1158 if (!wallet.fFileBacked)
1162 CRITICAL_BLOCK(cs_db)
1164 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1166 // Flush log data to the dat file
1167 CloseDb(wallet.strWalletFile);
1168 dbenv.txn_checkpoint(0, 0, 0);
1169 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1170 mapFileUseCount.erase(wallet.strWalletFile);
1173 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1174 filesystem::path pathDest(strDest);
1175 if (filesystem::is_directory(pathDest))
1176 pathDest = pathDest / wallet.strWalletFile;
1179 #if BOOST_VERSION >= 104000
1180 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1182 filesystem::copy_file(pathSrc, pathDest);
1184 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1186 } catch(const filesystem::filesystem_error &e) {
1187 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());