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 filesystem::path pathLogDir(strDataDir + "/database");
83 pathLogDir.make_preferred();
84 filesystem::create_directory(pathLogDir);
85 filesystem::path pathErrorFile(strDataDir + "/db.log");
86 pathErrorFile.make_preferred();
87 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
89 int nDbCache = GetArg("-dbcache", 25);
90 dbenv.set_lg_dir(pathLogDir.string().c_str());
91 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
92 dbenv.set_lg_bsize(1048576);
93 dbenv.set_lg_max(10485760);
94 dbenv.set_lk_max_locks(10000);
95 dbenv.set_lk_max_objects(10000);
96 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
97 dbenv.set_flags(DB_AUTO_COMMIT, 1);
98 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
99 ret = dbenv.open(strDataDir.c_str(),
109 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
114 ++mapFileUseCount[strFile];
115 pdb = mapDb[strFile];
118 pdb = new Db(&dbenv, 0);
120 ret = pdb->open(NULL, // Txn pointer
122 "main", // Logical db name
123 DB_BTREE, // Database type
133 --mapFileUseCount[strFile];
136 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
139 if (fCreate && !Exists(string("version")))
141 bool fTmp = fReadOnly;
143 WriteVersion(CLIENT_VERSION);
147 mapDb[strFile] = pdb;
157 vTxn.front()->abort();
161 // Flush database activity from memory pool to disk log
162 unsigned int nMinutes = 0;
165 if (strFile == "addr.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
647 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
651 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
652 if (!mapBlockPos.count(posFind))
654 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
655 pindexFork = pindex->pprev;
657 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
660 CTransaction txSpend;
661 if (!txSpend.ReadFromDisk(txpos))
663 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
664 pindexFork = pindex->pprev;
666 else if (!txSpend.CheckTransaction())
668 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
669 pindexFork = pindex->pprev;
674 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
675 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
679 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
680 pindexFork = pindex->pprev;
688 // check level 5: check whether all prevouts are marked spent
690 BOOST_FOREACH(const CTxIn &txin, tx.vin)
693 if (ReadTxIndex(txin.prevout.hash, txindex))
694 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
696 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
697 pindexFork = pindex->pprev;
705 // Reorg back to the fork
706 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
708 if (!block.ReadFromDisk(pindexFork))
709 return error("LoadBlockIndex() : block.ReadFromDisk failed");
711 block.SetBestChain(txdb, pindexFork);
725 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
727 return Write(string("addrman"), addrman);
730 bool CAddrDB::LoadAddresses()
732 if (Read(string("addrman"), addrman))
734 printf("Loaded %i addresses\n", addrman.size());
738 // Read pre-0.6 addr records
740 vector<CAddress> vAddr;
741 vector<vector<unsigned char> > vDelete;
744 Dbc* pcursor = GetCursor();
753 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
754 if (ret == DB_NOTFOUND)
762 if (strType == "addr")
766 vAddr.push_back(addr);
771 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
772 printf("Loaded %i addresses\n", addrman.size());
774 // Note: old records left; we ran into hangs-on-startup
775 // bugs for some users who (we think) were running after
776 // an unclean shutdown.
783 return CAddrDB("cr+").LoadAddresses();
793 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
796 return Write(make_pair(string("name"), strAddress), strName);
799 bool CWalletDB::EraseName(const string& strAddress)
801 // This should only be used for sending addresses, never for receiving addresses,
802 // receiving addresses must always have an address book entry if they're not change return.
804 return Erase(make_pair(string("name"), strAddress));
807 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
810 return Read(make_pair(string("acc"), strAccount), account);
813 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
815 return Write(make_pair(string("acc"), strAccount), account);
818 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
820 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
823 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
825 list<CAccountingEntry> entries;
826 ListAccountCreditDebit(strAccount, entries);
828 int64 nCreditDebit = 0;
829 BOOST_FOREACH (const CAccountingEntry& entry, entries)
830 nCreditDebit += entry.nCreditDebit;
835 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
837 bool fAllAccounts = (strAccount == "*");
839 Dbc* pcursor = GetCursor();
841 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
842 unsigned int fFlags = DB_SET_RANGE;
847 if (fFlags == DB_SET_RANGE)
848 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
850 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
852 if (ret == DB_NOTFOUND)
857 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
863 if (strType != "acentry")
865 CAccountingEntry acentry;
866 ssKey >> acentry.strAccount;
867 if (!fAllAccounts && acentry.strAccount != strAccount)
871 entries.push_back(acentry);
878 int CWalletDB::LoadWallet(CWallet* pwallet)
880 pwallet->vchDefaultKey.clear();
881 int nFileVersion = 0;
882 vector<uint256> vWalletUpgrade;
883 bool fIsEncrypted = false;
885 //// todo: shouldn't we catch exceptions and try to recover and continue?
887 LOCK(pwallet->cs_wallet);
889 if (Read((string)"minversion", nMinVersion))
891 if (nMinVersion > CLIENT_VERSION)
893 pwallet->LoadMinVersion(nMinVersion);
897 Dbc* pcursor = GetCursor();
900 printf("Error getting wallet database cursor\n");
909 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
910 if (ret == DB_NOTFOUND)
914 printf("Error reading next record from wallet database\n");
919 // Taking advantage of the fact that pair serialization
920 // is just the two items serialized one after the other
923 if (strType == "name")
927 ssValue >> pwallet->mapAddressBook[strAddress];
929 else if (strType == "tx")
933 CWalletTx& wtx = pwallet->mapWallet[hash];
935 wtx.BindWallet(pwallet);
937 if (wtx.GetHash() != hash)
938 printf("Error in wallet.dat, hash mismatch\n");
940 // Undo serialize changes in 31600
941 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
943 if (!ssValue.empty())
947 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
948 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
949 wtx.fTimeReceivedIsTxTime = fTmp;
953 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
954 wtx.fTimeReceivedIsTxTime = 0;
956 vWalletUpgrade.push_back(hash);
960 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
961 //printf(" %12I64d %s %s %s\n",
962 // wtx.vout[0].nValue,
963 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
964 // wtx.hashBlock.ToString().substr(0,20).c_str(),
965 // wtx.mapValue["message"].c_str());
967 else if (strType == "acentry")
973 if (nNumber > nAccountingEntryNumber)
974 nAccountingEntryNumber = nNumber;
976 else if (strType == "key" || strType == "wkey")
978 vector<unsigned char> vchPubKey;
981 if (strType == "key")
985 key.SetPubKey(vchPubKey);
986 key.SetPrivKey(pkey);
987 if (key.GetPubKey() != vchPubKey)
989 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
994 printf("Error reading wallet database: invalid CPrivKey\n");
1002 key.SetPubKey(vchPubKey);
1003 key.SetPrivKey(wkey.vchPrivKey);
1004 if (key.GetPubKey() != vchPubKey)
1006 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1011 printf("Error reading wallet database: invalid CWalletKey\n");
1015 if (!pwallet->LoadKey(key))
1017 printf("Error reading wallet database: LoadKey failed\n");
1021 else if (strType == "mkey")
1025 CMasterKey kMasterKey;
1026 ssValue >> kMasterKey;
1027 if(pwallet->mapMasterKeys.count(nID) != 0)
1029 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1032 pwallet->mapMasterKeys[nID] = kMasterKey;
1033 if (pwallet->nMasterKeyMaxID < nID)
1034 pwallet->nMasterKeyMaxID = nID;
1036 else if (strType == "ckey")
1038 vector<unsigned char> vchPubKey;
1040 vector<unsigned char> vchPrivKey;
1041 ssValue >> vchPrivKey;
1042 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1044 printf("Error reading wallet database: LoadCryptedKey failed\n");
1047 fIsEncrypted = true;
1049 else if (strType == "defaultkey")
1051 ssValue >> pwallet->vchDefaultKey;
1053 else if (strType == "pool")
1057 pwallet->setKeyPool.insert(nIndex);
1059 else if (strType == "version")
1061 ssValue >> nFileVersion;
1062 if (nFileVersion == 10300)
1065 else if (strType == "cscript")
1071 if (!pwallet->LoadCScript(script))
1073 printf("Error reading wallet database: LoadCScript failed\n");
1081 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1082 WriteTx(hash, pwallet->mapWallet[hash]);
1084 printf("nFileVersion = %d\n", nFileVersion);
1087 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1088 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1089 return DB_NEED_REWRITE;
1091 if (nFileVersion < CLIENT_VERSION) // Update
1093 // Get rid of old debug.log file in current directory
1094 if (nFileVersion <= 105 && !pszSetDataDir[0])
1095 unlink("debug.log");
1097 WriteVersion(CLIENT_VERSION);
1103 void ThreadFlushWalletDB(void* parg)
1105 const string& strFile = ((const string*)parg)[0];
1106 static bool fOneThread;
1110 if (!GetBoolArg("-flushwallet", true))
1113 unsigned int nLastSeen = nWalletDBUpdated;
1114 unsigned int nLastFlushed = nWalletDBUpdated;
1115 int64 nLastWalletUpdate = GetTime();
1120 if (nLastSeen != nWalletDBUpdated)
1122 nLastSeen = nWalletDBUpdated;
1123 nLastWalletUpdate = GetTime();
1126 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1128 TRY_LOCK(cs_db,lockDb);
1131 // Don't do this if any databases are in use
1133 map<string, int>::iterator mi = mapFileUseCount.begin();
1134 while (mi != mapFileUseCount.end())
1136 nRefCount += (*mi).second;
1140 if (nRefCount == 0 && !fShutdown)
1142 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1143 if (mi != mapFileUseCount.end())
1145 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1146 printf("Flushing wallet.dat\n");
1147 nLastFlushed = nWalletDBUpdated;
1148 int64 nStart = GetTimeMillis();
1150 // Flush wallet.dat so it's self contained
1152 dbenv.txn_checkpoint(0, 0, 0);
1153 dbenv.lsn_reset(strFile.c_str(), 0);
1155 mapFileUseCount.erase(mi++);
1156 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1164 bool BackupWallet(const CWallet& wallet, const string& strDest)
1166 if (!wallet.fFileBacked)
1172 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1174 // Flush log data to the dat file
1175 CloseDb(wallet.strWalletFile);
1176 dbenv.txn_checkpoint(0, 0, 0);
1177 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1178 mapFileUseCount.erase(wallet.strWalletFile);
1181 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1182 pathSrc.make_preferred();
1183 filesystem::path pathDest(strDest);
1184 pathDest.make_preferred();
1185 if (filesystem::is_directory(pathDest))
1186 pathDest = pathDest / wallet.strWalletFile;
1189 #if BOOST_VERSION >= 104000
1190 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1192 filesystem::copy_file(pathSrc, pathDest);
1194 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1196 } catch(const filesystem::filesystem_error &e) {
1197 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());