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().string().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 filesystem::path pathDataDir = GetDataDir();
82 filesystem::path pathLogDir = pathDataDir / "database";
83 filesystem::create_directory(pathLogDir);
84 filesystem::path pathErrorFile = pathDataDir / "db.log";
85 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
87 int nDbCache = GetArg("-dbcache", 25);
88 dbenv.set_lg_dir(pathLogDir.string().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(pathErrorFile.string().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(pathDataDir.string().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
131 --mapFileUseCount[strFile];
134 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
137 if (fCreate && !Exists(string("version")))
139 bool fTmp = fReadOnly;
141 WriteVersion(CLIENT_VERSION);
145 mapDb[strFile] = pdb;
155 vTxn.front()->abort();
159 // Flush database activity from memory pool to disk log
160 unsigned int nMinutes = 0;
163 if (strFile == "addr.dat")
165 if (strFile == "blkindex.dat")
167 if (strFile == "blkindex.dat" && IsInitialBlockDownload())
170 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
174 --mapFileUseCount[strFile];
178 void static CloseDb(const string& strFile)
182 if (mapDb[strFile] != NULL)
184 // Close the database handle
185 Db* pdb = mapDb[strFile];
188 mapDb[strFile] = NULL;
193 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
199 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
201 // Flush log data to the dat file
203 dbenv.txn_checkpoint(0, 0, 0);
204 dbenv.lsn_reset(strFile.c_str(), 0);
205 mapFileUseCount.erase(strFile);
207 bool fSuccess = true;
208 printf("Rewriting %s...\n", strFile.c_str());
209 string strFileRes = strFile + ".rewrite";
210 { // surround usage of db with extra {}
211 CDB db(strFile.c_str(), "r");
212 Db* pdbCopy = new Db(&dbenv, 0);
214 int ret = pdbCopy->open(NULL, // Txn pointer
215 strFileRes.c_str(), // Filename
216 "main", // Logical db name
217 DB_BTREE, // Database type
222 printf("Cannot create database file %s\n", strFileRes.c_str());
226 Dbc* pcursor = db.GetCursor();
232 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
233 if (ret == DB_NOTFOUND)
245 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
247 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
251 ssValue << CLIENT_VERSION;
253 Dbt datKey(&ssKey[0], ssKey.size());
254 Dbt datValue(&ssValue[0], ssValue.size());
255 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
263 if (pdbCopy->close(0))
271 if (dbA.remove(strFile.c_str(), NULL, 0))
274 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
278 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
288 void DBFlush(bool fShutdown)
290 // Flush log data to the actual data file
291 // on all files that are not in use
292 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
297 map<string, int>::iterator mi = mapFileUseCount.begin();
298 while (mi != mapFileUseCount.end())
300 string strFile = (*mi).first;
301 int nRefCount = (*mi).second;
302 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
305 // Move log data to the dat file
307 dbenv.txn_checkpoint(0, 0, 0);
308 printf("%s flush\n", strFile.c_str());
309 dbenv.lsn_reset(strFile.c_str(), 0);
310 mapFileUseCount.erase(mi++);
318 if (mapFileUseCount.empty())
320 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
336 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
340 return Read(make_pair(string("tx"), hash), txindex);
343 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
346 return Write(make_pair(string("tx"), hash), txindex);
349 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
354 uint256 hash = tx.GetHash();
355 CTxIndex txindex(pos, tx.vout.size());
356 return Write(make_pair(string("tx"), hash), txindex);
359 bool CTxDB::EraseTxIndex(const CTransaction& tx)
362 uint256 hash = tx.GetHash();
364 return Erase(make_pair(string("tx"), hash));
367 bool CTxDB::ContainsTx(uint256 hash)
370 return Exists(make_pair(string("tx"), hash));
373 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
379 Dbc* pcursor = GetCursor();
383 unsigned int fFlags = DB_SET_RANGE;
388 if (fFlags == DB_SET_RANGE)
389 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
391 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
393 if (ret == DB_NOTFOUND)
405 ssKey >> strType >> hashItem >> pos;
407 ssValue >> nItemHeight;
410 if (strType != "owner" || hashItem != hash160)
412 if (nItemHeight >= nMinHeight)
414 vtx.resize(vtx.size()+1);
415 if (!vtx.back().ReadFromDisk(pos))
427 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
431 if (!ReadTxIndex(hash, txindex))
433 return (tx.ReadFromDisk(txindex.pos));
436 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
439 return ReadDiskTx(hash, tx, txindex);
442 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
444 return ReadDiskTx(outpoint.hash, tx, txindex);
447 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
450 return ReadDiskTx(outpoint.hash, tx, txindex);
453 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
455 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
458 bool CTxDB::EraseBlockIndex(uint256 hash)
460 return Erase(make_pair(string("blockindex"), hash));
463 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
465 return Read(string("hashBestChain"), hashBestChain);
468 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
470 return Write(string("hashBestChain"), hashBestChain);
473 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
475 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
478 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
480 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
483 CBlockIndex static * InsertBlockIndex(uint256 hash)
489 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
490 if (mi != mapBlockIndex.end())
494 CBlockIndex* pindexNew = new CBlockIndex();
496 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
497 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
498 pindexNew->phashBlock = &((*mi).first);
503 bool CTxDB::LoadBlockIndex()
505 // Get database cursor
506 Dbc* pcursor = GetCursor();
510 // Load mapBlockIndex
511 unsigned int fFlags = DB_SET_RANGE;
516 if (fFlags == DB_SET_RANGE)
517 ssKey << make_pair(string("blockindex"), uint256(0));
519 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
521 if (ret == DB_NOTFOUND)
529 if (strType == "blockindex")
531 CDiskBlockIndex diskindex;
532 ssValue >> diskindex;
534 // Construct block index object
535 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
536 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
537 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
538 pindexNew->nFile = diskindex.nFile;
539 pindexNew->nBlockPos = diskindex.nBlockPos;
540 pindexNew->nHeight = diskindex.nHeight;
541 pindexNew->nVersion = diskindex.nVersion;
542 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
543 pindexNew->nTime = diskindex.nTime;
544 pindexNew->nBits = diskindex.nBits;
545 pindexNew->nNonce = diskindex.nNonce;
547 // Watch for genesis block
548 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
549 pindexGenesisBlock = pindexNew;
551 if (!pindexNew->CheckIndex())
552 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
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 int nCheckLevel = GetArg("-checklevel", 1);
595 int nCheckDepth = GetArg( "-checkblocks", 2500);
596 if (nCheckDepth == 0)
597 nCheckDepth = 1000000000; // suffices until the year 19000
598 if (nCheckDepth > nBestHeight)
599 nCheckDepth = nBestHeight;
600 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
601 CBlockIndex* pindexFork = NULL;
602 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
603 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
605 if (pindex->nHeight < nBestHeight-nCheckDepth)
608 if (!block.ReadFromDisk(pindex))
609 return error("LoadBlockIndex() : block.ReadFromDisk failed");
610 // check level 1: verify block validity
611 if (nCheckLevel>0 && !block.CheckBlock())
613 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
614 pindexFork = pindex->pprev;
616 // check level 2: verify transaction index validity
619 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
620 mapBlockPos[pos] = pindex;
621 BOOST_FOREACH(const CTransaction &tx, block.vtx)
623 uint256 hashTx = tx.GetHash();
625 if (ReadTxIndex(hashTx, txindex))
627 // check level 3: checker transaction hashes
628 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
630 // either an error or a duplicate transaction
631 CTransaction txFound;
632 if (!txFound.ReadFromDisk(txindex.pos))
634 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
635 pindexFork = pindex->pprev;
638 if (txFound.GetHash() != hashTx) // not a duplicate tx
640 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
641 pindexFork = pindex->pprev;
644 // check level 4: check whether spent txouts were spent within the main chain
648 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
652 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
653 if (!mapBlockPos.count(posFind))
655 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
656 pindexFork = pindex->pprev;
658 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
661 CTransaction txSpend;
662 if (!txSpend.ReadFromDisk(txpos))
664 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
665 pindexFork = pindex->pprev;
667 else if (!txSpend.CheckTransaction())
669 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
670 pindexFork = pindex->pprev;
675 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
676 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
680 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
681 pindexFork = pindex->pprev;
690 // check level 5: check whether all prevouts are marked spent
693 BOOST_FOREACH(const CTxIn &txin, tx.vin)
696 if (ReadTxIndex(txin.prevout.hash, txindex))
697 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
699 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
700 pindexFork = pindex->pprev;
709 // Reorg back to the fork
710 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
712 if (!block.ReadFromDisk(pindexFork))
713 return error("LoadBlockIndex() : block.ReadFromDisk failed");
715 block.SetBestChain(txdb, pindexFork);
729 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
731 return Write(string("addrman"), addrman);
734 bool CAddrDB::LoadAddresses()
736 if (Read(string("addrman"), addrman))
738 printf("Loaded %i addresses\n", addrman.size());
742 // Read pre-0.6 addr records
744 vector<CAddress> vAddr;
745 vector<vector<unsigned char> > vDelete;
748 Dbc* pcursor = GetCursor();
757 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
758 if (ret == DB_NOTFOUND)
766 if (strType == "addr")
770 vAddr.push_back(addr);
775 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
776 printf("Loaded %i addresses\n", addrman.size());
778 // Note: old records left; we ran into hangs-on-startup
779 // bugs for some users who (we think) were running after
780 // an unclean shutdown.
787 return CAddrDB("cr+").LoadAddresses();
797 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
800 return Write(make_pair(string("name"), strAddress), strName);
803 bool CWalletDB::EraseName(const string& strAddress)
805 // This should only be used for sending addresses, never for receiving addresses,
806 // receiving addresses must always have an address book entry if they're not change return.
808 return Erase(make_pair(string("name"), strAddress));
811 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
814 return Read(make_pair(string("acc"), strAccount), account);
817 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
819 return Write(make_pair(string("acc"), strAccount), account);
822 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
824 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
827 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
829 list<CAccountingEntry> entries;
830 ListAccountCreditDebit(strAccount, entries);
832 int64 nCreditDebit = 0;
833 BOOST_FOREACH (const CAccountingEntry& entry, entries)
834 nCreditDebit += entry.nCreditDebit;
839 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
841 bool fAllAccounts = (strAccount == "*");
843 Dbc* pcursor = GetCursor();
845 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
846 unsigned int fFlags = DB_SET_RANGE;
851 if (fFlags == DB_SET_RANGE)
852 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
854 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
856 if (ret == DB_NOTFOUND)
861 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
867 if (strType != "acentry")
869 CAccountingEntry acentry;
870 ssKey >> acentry.strAccount;
871 if (!fAllAccounts && acentry.strAccount != strAccount)
875 entries.push_back(acentry);
882 int CWalletDB::LoadWallet(CWallet* pwallet)
884 pwallet->vchDefaultKey.clear();
885 int nFileVersion = 0;
886 vector<uint256> vWalletUpgrade;
887 bool fIsEncrypted = false;
889 //// todo: shouldn't we catch exceptions and try to recover and continue?
891 LOCK(pwallet->cs_wallet);
893 if (Read((string)"minversion", nMinVersion))
895 if (nMinVersion > CLIENT_VERSION)
897 pwallet->LoadMinVersion(nMinVersion);
901 Dbc* pcursor = GetCursor();
904 printf("Error getting wallet database cursor\n");
913 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
914 if (ret == DB_NOTFOUND)
918 printf("Error reading next record from wallet database\n");
923 // Taking advantage of the fact that pair serialization
924 // is just the two items serialized one after the other
927 if (strType == "name")
931 ssValue >> pwallet->mapAddressBook[strAddress];
933 else if (strType == "tx")
937 CWalletTx& wtx = pwallet->mapWallet[hash];
939 wtx.BindWallet(pwallet);
941 if (wtx.GetHash() != hash)
942 printf("Error in wallet.dat, hash mismatch\n");
944 // Undo serialize changes in 31600
945 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
947 if (!ssValue.empty())
951 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
952 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
953 wtx.fTimeReceivedIsTxTime = fTmp;
957 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
958 wtx.fTimeReceivedIsTxTime = 0;
960 vWalletUpgrade.push_back(hash);
964 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
965 //printf(" %12I64d %s %s %s\n",
966 // wtx.vout[0].nValue,
967 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
968 // wtx.hashBlock.ToString().substr(0,20).c_str(),
969 // wtx.mapValue["message"].c_str());
971 else if (strType == "acentry")
977 if (nNumber > nAccountingEntryNumber)
978 nAccountingEntryNumber = nNumber;
980 else if (strType == "key" || strType == "wkey")
982 vector<unsigned char> vchPubKey;
985 if (strType == "key")
989 key.SetPubKey(vchPubKey);
990 key.SetPrivKey(pkey);
991 if (key.GetPubKey() != vchPubKey)
993 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
998 printf("Error reading wallet database: invalid CPrivKey\n");
1006 key.SetPubKey(vchPubKey);
1007 key.SetPrivKey(wkey.vchPrivKey);
1008 if (key.GetPubKey() != vchPubKey)
1010 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1015 printf("Error reading wallet database: invalid CWalletKey\n");
1019 if (!pwallet->LoadKey(key))
1021 printf("Error reading wallet database: LoadKey failed\n");
1025 else if (strType == "mkey")
1029 CMasterKey kMasterKey;
1030 ssValue >> kMasterKey;
1031 if(pwallet->mapMasterKeys.count(nID) != 0)
1033 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1036 pwallet->mapMasterKeys[nID] = kMasterKey;
1037 if (pwallet->nMasterKeyMaxID < nID)
1038 pwallet->nMasterKeyMaxID = nID;
1040 else if (strType == "ckey")
1042 vector<unsigned char> vchPubKey;
1044 vector<unsigned char> vchPrivKey;
1045 ssValue >> vchPrivKey;
1046 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1048 printf("Error reading wallet database: LoadCryptedKey failed\n");
1051 fIsEncrypted = true;
1053 else if (strType == "defaultkey")
1055 ssValue >> pwallet->vchDefaultKey;
1057 else if (strType == "pool")
1061 pwallet->setKeyPool.insert(nIndex);
1063 else if (strType == "version")
1065 ssValue >> nFileVersion;
1066 if (nFileVersion == 10300)
1069 else if (strType == "cscript")
1075 if (!pwallet->LoadCScript(script))
1077 printf("Error reading wallet database: LoadCScript failed\n");
1085 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1086 WriteTx(hash, pwallet->mapWallet[hash]);
1088 printf("nFileVersion = %d\n", nFileVersion);
1091 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1092 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1093 return DB_NEED_REWRITE;
1095 if (nFileVersion < CLIENT_VERSION) // Update
1096 WriteVersion(CLIENT_VERSION);
1101 void ThreadFlushWalletDB(void* parg)
1103 const string& strFile = ((const string*)parg)[0];
1104 static bool fOneThread;
1108 if (!GetBoolArg("-flushwallet", true))
1111 unsigned int nLastSeen = nWalletDBUpdated;
1112 unsigned int nLastFlushed = nWalletDBUpdated;
1113 int64 nLastWalletUpdate = GetTime();
1118 if (nLastSeen != nWalletDBUpdated)
1120 nLastSeen = nWalletDBUpdated;
1121 nLastWalletUpdate = GetTime();
1124 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1126 TRY_LOCK(cs_db,lockDb);
1129 // Don't do this if any databases are in use
1131 map<string, int>::iterator mi = mapFileUseCount.begin();
1132 while (mi != mapFileUseCount.end())
1134 nRefCount += (*mi).second;
1138 if (nRefCount == 0 && !fShutdown)
1140 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1141 if (mi != mapFileUseCount.end())
1143 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1144 printf("Flushing wallet.dat\n");
1145 nLastFlushed = nWalletDBUpdated;
1146 int64 nStart = GetTimeMillis();
1148 // Flush wallet.dat so it's self contained
1150 dbenv.txn_checkpoint(0, 0, 0);
1151 dbenv.lsn_reset(strFile.c_str(), 0);
1153 mapFileUseCount.erase(mi++);
1154 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1162 bool BackupWallet(const CWallet& wallet, const string& strDest)
1164 if (!wallet.fFileBacked)
1170 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1172 // Flush log data to the dat file
1173 CloseDb(wallet.strWalletFile);
1174 dbenv.txn_checkpoint(0, 0, 0);
1175 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1176 mapFileUseCount.erase(wallet.strWalletFile);
1179 filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
1180 filesystem::path pathDest(strDest);
1181 if (filesystem::is_directory(pathDest))
1182 pathDest /= wallet.strWalletFile;
1185 #if BOOST_VERSION >= 104000
1186 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1188 filesystem::copy_file(pathSrc, pathDest);
1190 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1192 } catch(const filesystem::filesystem_error &e) {
1193 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());