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;
31 static int64 nTxn = 0;
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 int nDbCache = GetArg("-dbcache", 25);
89 dbenv.set_lg_dir(strLogDir.c_str());
90 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
91 dbenv.set_lg_bsize(1048576);
92 dbenv.set_lg_max(10485760);
93 dbenv.set_lk_max_locks(10000);
94 dbenv.set_lk_max_objects(10000);
95 dbenv.set_errfile(fopen(strErrorFile.c_str(), "a")); /// debug
96 dbenv.set_flags(DB_AUTO_COMMIT, 1);
97 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
98 ret = dbenv.open(strDataDir.c_str(),
108 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
113 ++mapFileUseCount[strFile];
114 pdb = mapDb[strFile];
117 pdb = new Db(&dbenv, 0);
119 ret = pdb->open(NULL, // Txn pointer
121 "main", // Logical db name
122 DB_BTREE, // Database type
130 CRITICAL_BLOCK(cs_db)
131 --mapFileUseCount[strFile];
133 throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
136 if (fCreate && !Exists(string("version")))
138 bool fTmp = fReadOnly;
140 WriteVersion(CLIENT_VERSION);
144 mapDb[strFile] = pdb;
154 vTxn.front()->abort();
158 // Flush database activity from memory pool to disk log
159 unsigned int nMinutes = 0;
162 if (strFile == "addr.dat")
164 if (strFile == "blkindex.dat" && IsInitialBlockDownload())
167 if (nMinutes == 0 || nTxn > 200000)
173 dbenv.txn_checkpoint(0, nMinutes, 0);
175 CRITICAL_BLOCK(cs_db)
176 --mapFileUseCount[strFile];
179 void static CloseDb(const string& strFile)
181 CRITICAL_BLOCK(cs_db)
183 if (mapDb[strFile] != NULL)
185 // Close the database handle
186 Db* pdb = mapDb[strFile];
189 mapDb[strFile] = NULL;
194 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
198 CRITICAL_BLOCK(cs_db)
200 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
202 // Flush log data to the dat file
204 dbenv.txn_checkpoint(0, 0, 0);
205 dbenv.lsn_reset(strFile.c_str(), 0);
206 mapFileUseCount.erase(strFile);
208 bool fSuccess = true;
209 printf("Rewriting %s...\n", strFile.c_str());
210 string strFileRes = strFile + ".rewrite";
211 { // surround usage of db with extra {}
212 CDB db(strFile.c_str(), "r");
213 Db* pdbCopy = new Db(&dbenv, 0);
215 int ret = pdbCopy->open(NULL, // Txn pointer
216 strFileRes.c_str(), // Filename
217 "main", // Logical db name
218 DB_BTREE, // Database type
223 printf("Cannot create database file %s\n", strFileRes.c_str());
227 Dbc* pcursor = db.GetCursor();
233 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
234 if (ret == DB_NOTFOUND)
246 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
248 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
252 ssValue << CLIENT_VERSION;
254 Dbt datKey(&ssKey[0], ssKey.size());
255 Dbt datValue(&ssValue[0], ssValue.size());
256 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
264 if (pdbCopy->close(0))
272 if (dbA.remove(strFile.c_str(), NULL, 0))
275 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
279 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
289 void DBFlush(bool fShutdown)
291 // Flush log data to the actual data file
292 // on all files that are not in use
293 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
296 CRITICAL_BLOCK(cs_db)
298 map<string, int>::iterator mi = mapFileUseCount.begin();
299 while (mi != mapFileUseCount.end())
301 string strFile = (*mi).first;
302 int nRefCount = (*mi).second;
303 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
306 // Move log data to the dat file
308 dbenv.txn_checkpoint(0, 0, 0);
309 printf("%s flush\n", strFile.c_str());
310 dbenv.lsn_reset(strFile.c_str(), 0);
311 mapFileUseCount.erase(mi++);
319 if (mapFileUseCount.empty())
321 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
337 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
341 return Read(make_pair(string("tx"), hash), txindex);
344 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
348 return Write(make_pair(string("tx"), hash), txindex);
351 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
356 uint256 hash = tx.GetHash();
357 CTxIndex txindex(pos, tx.vout.size());
359 return Write(make_pair(string("tx"), hash), txindex);
362 bool CTxDB::EraseTxIndex(const CTransaction& tx)
365 uint256 hash = tx.GetHash();
367 return Erase(make_pair(string("tx"), hash));
370 bool CTxDB::ContainsTx(uint256 hash)
373 return Exists(make_pair(string("tx"), hash));
376 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
382 Dbc* pcursor = GetCursor();
386 unsigned int fFlags = DB_SET_RANGE;
391 if (fFlags == DB_SET_RANGE)
392 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
394 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
396 if (ret == DB_NOTFOUND)
408 ssKey >> strType >> hashItem >> pos;
410 ssValue >> nItemHeight;
413 if (strType != "owner" || hashItem != hash160)
415 if (nItemHeight >= nMinHeight)
417 vtx.resize(vtx.size()+1);
418 if (!vtx.back().ReadFromDisk(pos))
430 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
434 if (!ReadTxIndex(hash, txindex))
436 return (tx.ReadFromDisk(txindex.pos));
439 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
442 return ReadDiskTx(hash, tx, txindex);
445 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
447 return ReadDiskTx(outpoint.hash, tx, txindex);
450 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
453 return ReadDiskTx(outpoint.hash, tx, txindex);
456 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
458 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
461 bool CTxDB::EraseBlockIndex(uint256 hash)
463 return Erase(make_pair(string("blockindex"), hash));
466 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
468 return Read(string("hashBestChain"), hashBestChain);
471 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
473 return Write(string("hashBestChain"), hashBestChain);
476 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
478 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
481 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
483 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
486 CBlockIndex static * InsertBlockIndex(uint256 hash)
492 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
493 if (mi != mapBlockIndex.end())
497 CBlockIndex* pindexNew = new CBlockIndex();
499 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
500 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
501 pindexNew->phashBlock = &((*mi).first);
506 bool CTxDB::LoadBlockIndex()
508 // Get database cursor
509 Dbc* pcursor = GetCursor();
513 // Load mapBlockIndex
514 unsigned int fFlags = DB_SET_RANGE;
519 if (fFlags == DB_SET_RANGE)
520 ssKey << make_pair(string("blockindex"), uint256(0));
522 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
524 if (ret == DB_NOTFOUND)
532 if (strType == "blockindex")
534 CDiskBlockIndex diskindex;
535 ssValue >> diskindex;
537 // Construct block index object
538 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
539 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
540 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
541 pindexNew->nFile = diskindex.nFile;
542 pindexNew->nBlockPos = diskindex.nBlockPos;
543 pindexNew->nHeight = diskindex.nHeight;
544 pindexNew->nVersion = diskindex.nVersion;
545 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
546 pindexNew->nTime = diskindex.nTime;
547 pindexNew->nBits = diskindex.nBits;
548 pindexNew->nNonce = diskindex.nNonce;
550 // Watch for genesis block
551 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
552 pindexGenesisBlock = pindexNew;
554 if (!pindexNew->CheckIndex())
555 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
564 // Calculate bnChainWork
565 vector<pair<int, CBlockIndex*> > vSortedByHeight;
566 vSortedByHeight.reserve(mapBlockIndex.size());
567 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
569 CBlockIndex* pindex = item.second;
570 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
572 sort(vSortedByHeight.begin(), vSortedByHeight.end());
573 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
575 CBlockIndex* pindex = item.second;
576 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
579 // Load hashBestChain pointer to end of best chain
580 if (!ReadHashBestChain(hashBestChain))
582 if (pindexGenesisBlock == NULL)
584 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
586 if (!mapBlockIndex.count(hashBestChain))
587 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
588 pindexBest = mapBlockIndex[hashBestChain];
589 nBestHeight = pindexBest->nHeight;
590 bnBestChainWork = pindexBest->bnChainWork;
591 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
593 // Load bnBestInvalidWork, OK if it doesn't exist
594 ReadBestInvalidWork(bnBestInvalidWork);
596 // Verify blocks in the best chain
597 int nCheckLevel = GetArg("-checklevel", 1);
598 int nCheckDepth = GetArg( "-checkblocks", 2500);
599 if (nCheckDepth == 0)
600 nCheckDepth = 1000000000; // suffices until the year 19000
601 if (nCheckDepth > nBestHeight)
602 nCheckDepth = nBestHeight;
603 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
604 CBlockIndex* pindexFork = NULL;
605 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
606 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
608 if (pindex->nHeight < nBestHeight-nCheckDepth)
611 if (!block.ReadFromDisk(pindex))
612 return error("LoadBlockIndex() : block.ReadFromDisk failed");
613 // check level 1: verify block validity
614 if (nCheckLevel>0 && !block.CheckBlock())
616 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
617 pindexFork = pindex->pprev;
619 // check level 2: verify transaction index validity
622 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
623 mapBlockPos[pos] = pindex;
624 BOOST_FOREACH(const CTransaction &tx, block.vtx)
626 uint256 hashTx = tx.GetHash();
628 if (ReadTxIndex(hashTx, txindex))
630 // check level 3: checker transaction hashes
631 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
633 // either an error or a duplicate transaction
634 CTransaction txFound;
635 if (!txFound.ReadFromDisk(txindex.pos))
637 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
638 pindexFork = pindex->pprev;
641 if (txFound.GetHash() != hashTx) // not a duplicate tx
643 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
644 pindexFork = pindex->pprev;
647 // check level 4: check whether spent txouts were spent within the main chain
651 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
655 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
656 if (!mapBlockPos.count(posFind))
658 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
659 pindexFork = pindex->pprev;
661 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
664 CTransaction txSpend;
665 if (!txSpend.ReadFromDisk(txpos))
667 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
668 pindexFork = pindex->pprev;
670 else if (!txSpend.CheckTransaction())
672 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
673 pindexFork = pindex->pprev;
678 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
679 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
683 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
684 pindexFork = pindex->pprev;
693 // check level 5: check whether all prevouts are marked spent
696 BOOST_FOREACH(const CTxIn &txin, tx.vin)
699 if (ReadTxIndex(txin.prevout.hash, txindex))
700 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
702 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
703 pindexFork = pindex->pprev;
712 // Reorg back to the fork
713 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
715 if (!block.ReadFromDisk(pindexFork))
716 return error("LoadBlockIndex() : block.ReadFromDisk failed");
718 block.SetBestChain(txdb, pindexFork);
732 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
734 return Write(string("addrman"), addrman);
737 bool CAddrDB::LoadAddresses()
739 if (Read(string("addrman"), addrman))
741 printf("Loaded %i addresses\n", addrman.size());
745 // Read pre-0.6 addr records
747 vector<CAddress> vAddr;
748 vector<vector<unsigned char> > vDelete;
751 Dbc* pcursor = GetCursor();
760 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
761 if (ret == DB_NOTFOUND)
769 if (strType == "addr")
773 vAddr.push_back(addr);
778 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
779 printf("Loaded %i addresses\n", addrman.size());
781 // Note: old records left; we ran into hangs-on-startup
782 // bugs for some users who (we think) were running after
783 // an unclean shutdown.
790 return CAddrDB("cr+").LoadAddresses();
800 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
803 return Write(make_pair(string("name"), strAddress), strName);
806 bool CWalletDB::EraseName(const string& strAddress)
808 // This should only be used for sending addresses, never for receiving addresses,
809 // receiving addresses must always have an address book entry if they're not change return.
811 return Erase(make_pair(string("name"), strAddress));
814 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
817 return Read(make_pair(string("acc"), strAccount), account);
820 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
822 return Write(make_pair(string("acc"), strAccount), account);
825 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
827 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
830 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
832 list<CAccountingEntry> entries;
833 ListAccountCreditDebit(strAccount, entries);
835 int64 nCreditDebit = 0;
836 BOOST_FOREACH (const CAccountingEntry& entry, entries)
837 nCreditDebit += entry.nCreditDebit;
842 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
844 bool fAllAccounts = (strAccount == "*");
846 Dbc* pcursor = GetCursor();
848 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
849 unsigned int fFlags = DB_SET_RANGE;
854 if (fFlags == DB_SET_RANGE)
855 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
857 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
859 if (ret == DB_NOTFOUND)
864 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
870 if (strType != "acentry")
872 CAccountingEntry acentry;
873 ssKey >> acentry.strAccount;
874 if (!fAllAccounts && acentry.strAccount != strAccount)
878 entries.push_back(acentry);
885 int CWalletDB::LoadWallet(CWallet* pwallet)
887 pwallet->vchDefaultKey.clear();
888 int nFileVersion = 0;
889 vector<uint256> vWalletUpgrade;
890 bool fIsEncrypted = false;
892 //// todo: shouldn't we catch exceptions and try to recover and continue?
893 CRITICAL_BLOCK(pwallet->cs_wallet)
896 if (Read((string)"minversion", nMinVersion))
898 if (nMinVersion > CLIENT_VERSION)
900 pwallet->LoadMinVersion(nMinVersion);
904 Dbc* pcursor = GetCursor();
907 printf("Error getting wallet database cursor\n");
916 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
917 if (ret == DB_NOTFOUND)
921 printf("Error reading next record from wallet database\n");
926 // Taking advantage of the fact that pair serialization
927 // is just the two items serialized one after the other
930 if (strType == "name")
934 ssValue >> pwallet->mapAddressBook[strAddress];
936 else if (strType == "tx")
940 CWalletTx& wtx = pwallet->mapWallet[hash];
942 wtx.BindWallet(pwallet);
944 if (wtx.GetHash() != hash)
945 printf("Error in wallet.dat, hash mismatch\n");
947 // Undo serialize changes in 31600
948 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
950 if (!ssValue.empty())
954 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
955 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
956 wtx.fTimeReceivedIsTxTime = fTmp;
960 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
961 wtx.fTimeReceivedIsTxTime = 0;
963 vWalletUpgrade.push_back(hash);
967 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
968 //printf(" %12"PRI64d" %s %s %s\n",
969 // wtx.vout[0].nValue,
970 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
971 // wtx.hashBlock.ToString().substr(0,20).c_str(),
972 // wtx.mapValue["message"].c_str());
974 else if (strType == "acentry")
980 if (nNumber > nAccountingEntryNumber)
981 nAccountingEntryNumber = nNumber;
983 else if (strType == "key" || strType == "wkey")
985 vector<unsigned char> vchPubKey;
988 if (strType == "key")
992 key.SetPubKey(vchPubKey);
993 key.SetPrivKey(pkey);
994 if (key.GetPubKey() != vchPubKey)
996 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
1001 printf("Error reading wallet database: invalid CPrivKey\n");
1009 key.SetPubKey(vchPubKey);
1010 key.SetPrivKey(wkey.vchPrivKey);
1011 if (key.GetPubKey() != vchPubKey)
1013 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1018 printf("Error reading wallet database: invalid CWalletKey\n");
1022 if (!pwallet->LoadKey(key))
1024 printf("Error reading wallet database: LoadKey failed\n");
1028 else if (strType == "mkey")
1032 CMasterKey kMasterKey;
1033 ssValue >> kMasterKey;
1034 if(pwallet->mapMasterKeys.count(nID) != 0)
1036 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1039 pwallet->mapMasterKeys[nID] = kMasterKey;
1040 if (pwallet->nMasterKeyMaxID < nID)
1041 pwallet->nMasterKeyMaxID = nID;
1043 else if (strType == "ckey")
1045 vector<unsigned char> vchPubKey;
1047 vector<unsigned char> vchPrivKey;
1048 ssValue >> vchPrivKey;
1049 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1051 printf("Error reading wallet database: LoadCryptedKey failed\n");
1054 fIsEncrypted = true;
1056 else if (strType == "defaultkey")
1058 ssValue >> pwallet->vchDefaultKey;
1060 else if (strType == "pool")
1064 pwallet->setKeyPool.insert(nIndex);
1066 else if (strType == "version")
1068 ssValue >> nFileVersion;
1069 if (nFileVersion == 10300)
1072 else if (strType == "cscript")
1078 if (!pwallet->LoadCScript(script))
1080 printf("Error reading wallet database: LoadCScript failed\n");
1088 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1089 WriteTx(hash, pwallet->mapWallet[hash]);
1091 printf("nFileVersion = %d\n", nFileVersion);
1094 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1095 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1096 return DB_NEED_REWRITE;
1098 if (nFileVersion < CLIENT_VERSION) // Update
1100 // Get rid of old debug.log file in current directory
1101 if (nFileVersion <= 105 && !pszSetDataDir[0])
1102 unlink("debug.log");
1104 WriteVersion(CLIENT_VERSION);
1110 void ThreadFlushWalletDB(void* parg)
1112 const string& strFile = ((const string*)parg)[0];
1113 static bool fOneThread;
1117 if (!GetBoolArg("-flushwallet", true))
1120 unsigned int nLastSeen = nWalletDBUpdated;
1121 unsigned int nLastFlushed = nWalletDBUpdated;
1122 int64 nLastWalletUpdate = GetTime();
1127 if (nLastSeen != nWalletDBUpdated)
1129 nLastSeen = nWalletDBUpdated;
1130 nLastWalletUpdate = GetTime();
1133 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1135 TRY_CRITICAL_BLOCK(cs_db)
1137 // Don't do this if any databases are in use
1139 map<string, int>::iterator mi = mapFileUseCount.begin();
1140 while (mi != mapFileUseCount.end())
1142 nRefCount += (*mi).second;
1146 if (nRefCount == 0 && !fShutdown)
1148 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1149 if (mi != mapFileUseCount.end())
1151 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1152 printf("Flushing wallet.dat\n");
1153 nLastFlushed = nWalletDBUpdated;
1154 int64 nStart = GetTimeMillis();
1156 // Flush wallet.dat so it's self contained
1158 dbenv.txn_checkpoint(0, 0, 0);
1159 dbenv.lsn_reset(strFile.c_str(), 0);
1161 mapFileUseCount.erase(mi++);
1162 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1170 bool BackupWallet(const CWallet& wallet, const string& strDest)
1172 if (!wallet.fFileBacked)
1176 CRITICAL_BLOCK(cs_db)
1178 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1180 // Flush log data to the dat file
1181 CloseDb(wallet.strWalletFile);
1182 dbenv.txn_checkpoint(0, 0, 0);
1183 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1184 mapFileUseCount.erase(wallet.strWalletFile);
1187 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1188 filesystem::path pathDest(strDest);
1189 if (filesystem::is_directory(pathDest))
1190 pathDest = pathDest / wallet.strWalletFile;
1193 #if BOOST_VERSION >= 104000
1194 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1196 filesystem::copy_file(pathSrc, pathDest);
1198 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1200 } catch(const filesystem::filesystem_error &e) {
1201 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());