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())
166 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
168 CRITICAL_BLOCK(cs_db)
169 --mapFileUseCount[strFile];
172 void static CloseDb(const string& strFile)
174 CRITICAL_BLOCK(cs_db)
176 if (mapDb[strFile] != NULL)
178 // Close the database handle
179 Db* pdb = mapDb[strFile];
182 mapDb[strFile] = NULL;
187 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
191 CRITICAL_BLOCK(cs_db)
193 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
195 // Flush log data to the dat file
197 dbenv.txn_checkpoint(0, 0, 0);
198 dbenv.lsn_reset(strFile.c_str(), 0);
199 mapFileUseCount.erase(strFile);
201 bool fSuccess = true;
202 printf("Rewriting %s...\n", strFile.c_str());
203 string strFileRes = strFile + ".rewrite";
204 { // surround usage of db with extra {}
205 CDB db(strFile.c_str(), "r");
206 Db* pdbCopy = new Db(&dbenv, 0);
208 int ret = pdbCopy->open(NULL, // Txn pointer
209 strFileRes.c_str(), // Filename
210 "main", // Logical db name
211 DB_BTREE, // Database type
216 printf("Cannot create database file %s\n", strFileRes.c_str());
220 Dbc* pcursor = db.GetCursor();
226 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
227 if (ret == DB_NOTFOUND)
239 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
241 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
245 ssValue << CLIENT_VERSION;
247 Dbt datKey(&ssKey[0], ssKey.size());
248 Dbt datValue(&ssValue[0], ssValue.size());
249 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
257 if (pdbCopy->close(0))
265 if (dbA.remove(strFile.c_str(), NULL, 0))
268 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
272 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
282 void DBFlush(bool fShutdown)
284 // Flush log data to the actual data file
285 // on all files that are not in use
286 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
289 CRITICAL_BLOCK(cs_db)
291 map<string, int>::iterator mi = mapFileUseCount.begin();
292 while (mi != mapFileUseCount.end())
294 string strFile = (*mi).first;
295 int nRefCount = (*mi).second;
296 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
299 // Move log data to the dat file
301 dbenv.txn_checkpoint(0, 0, 0);
302 printf("%s flush\n", strFile.c_str());
303 dbenv.lsn_reset(strFile.c_str(), 0);
304 mapFileUseCount.erase(mi++);
312 if (mapFileUseCount.empty())
314 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
330 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
334 return Read(make_pair(string("tx"), hash), txindex);
337 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
340 return Write(make_pair(string("tx"), hash), txindex);
343 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
348 uint256 hash = tx.GetHash();
349 CTxIndex txindex(pos, tx.vout.size());
350 return Write(make_pair(string("tx"), hash), txindex);
353 bool CTxDB::EraseTxIndex(const CTransaction& tx)
356 uint256 hash = tx.GetHash();
358 return Erase(make_pair(string("tx"), hash));
361 bool CTxDB::ContainsTx(uint256 hash)
364 return Exists(make_pair(string("tx"), hash));
367 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
373 Dbc* pcursor = GetCursor();
377 unsigned int fFlags = DB_SET_RANGE;
382 if (fFlags == DB_SET_RANGE)
383 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
385 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
387 if (ret == DB_NOTFOUND)
399 ssKey >> strType >> hashItem >> pos;
401 ssValue >> nItemHeight;
404 if (strType != "owner" || hashItem != hash160)
406 if (nItemHeight >= nMinHeight)
408 vtx.resize(vtx.size()+1);
409 if (!vtx.back().ReadFromDisk(pos))
421 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
425 if (!ReadTxIndex(hash, txindex))
427 return (tx.ReadFromDisk(txindex.pos));
430 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
433 return ReadDiskTx(hash, tx, txindex);
436 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
438 return ReadDiskTx(outpoint.hash, tx, txindex);
441 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
444 return ReadDiskTx(outpoint.hash, tx, txindex);
447 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
449 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
452 bool CTxDB::EraseBlockIndex(uint256 hash)
454 return Erase(make_pair(string("blockindex"), hash));
457 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
459 return Read(string("hashBestChain"), hashBestChain);
462 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
464 return Write(string("hashBestChain"), hashBestChain);
467 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
469 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
472 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
474 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
477 CBlockIndex static * InsertBlockIndex(uint256 hash)
483 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
484 if (mi != mapBlockIndex.end())
488 CBlockIndex* pindexNew = new CBlockIndex();
490 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
491 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
492 pindexNew->phashBlock = &((*mi).first);
497 bool CTxDB::LoadBlockIndex()
499 // Get database cursor
500 Dbc* pcursor = GetCursor();
504 // Load mapBlockIndex
505 unsigned int fFlags = DB_SET_RANGE;
510 if (fFlags == DB_SET_RANGE)
511 ssKey << make_pair(string("blockindex"), uint256(0));
513 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
515 if (ret == DB_NOTFOUND)
523 if (strType == "blockindex")
525 CDiskBlockIndex diskindex;
526 ssValue >> diskindex;
528 // Construct block index object
529 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
530 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
531 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
532 pindexNew->nFile = diskindex.nFile;
533 pindexNew->nBlockPos = diskindex.nBlockPos;
534 pindexNew->nHeight = diskindex.nHeight;
535 pindexNew->nVersion = diskindex.nVersion;
536 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
537 pindexNew->nTime = diskindex.nTime;
538 pindexNew->nBits = diskindex.nBits;
539 pindexNew->nNonce = diskindex.nNonce;
541 // Watch for genesis block
542 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
543 pindexGenesisBlock = pindexNew;
545 if (!pindexNew->CheckIndex())
546 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
555 // Calculate bnChainWork
556 vector<pair<int, CBlockIndex*> > vSortedByHeight;
557 vSortedByHeight.reserve(mapBlockIndex.size());
558 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
560 CBlockIndex* pindex = item.second;
561 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
563 sort(vSortedByHeight.begin(), vSortedByHeight.end());
564 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
566 CBlockIndex* pindex = item.second;
567 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
570 // Load hashBestChain pointer to end of best chain
571 if (!ReadHashBestChain(hashBestChain))
573 if (pindexGenesisBlock == NULL)
575 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
577 if (!mapBlockIndex.count(hashBestChain))
578 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
579 pindexBest = mapBlockIndex[hashBestChain];
580 nBestHeight = pindexBest->nHeight;
581 bnBestChainWork = pindexBest->bnChainWork;
582 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
584 // Load bnBestInvalidWork, OK if it doesn't exist
585 ReadBestInvalidWork(bnBestInvalidWork);
587 // Verify blocks in the best chain
588 int nCheckLevel = GetArg("-checklevel", 1);
589 int nCheckDepth = GetArg( "-checkblocks", 2500);
590 if (nCheckDepth == 0)
591 nCheckDepth = 1000000000; // suffices until the year 19000
592 if (nCheckDepth > nBestHeight)
593 nCheckDepth = nBestHeight;
594 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
595 CBlockIndex* pindexFork = NULL;
596 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
597 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
599 if (pindex->nHeight < nBestHeight-nCheckDepth)
602 if (!block.ReadFromDisk(pindex))
603 return error("LoadBlockIndex() : block.ReadFromDisk failed");
604 // check level 1: verify block validity
605 if (nCheckLevel>0 && !block.CheckBlock())
607 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
608 pindexFork = pindex->pprev;
610 // check level 2: verify transaction index validity
613 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
614 mapBlockPos[pos] = pindex;
615 BOOST_FOREACH(const CTransaction &tx, block.vtx)
617 uint256 hashTx = tx.GetHash();
619 if (ReadTxIndex(hashTx, txindex))
621 // check level 3: checker transaction hashes
622 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
624 // either an error or a duplicate transaction
625 CTransaction txFound;
626 if (!txFound.ReadFromDisk(txindex.pos))
628 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
629 pindexFork = pindex->pprev;
632 if (txFound.GetHash() != hashTx) // not a duplicate tx
634 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
635 pindexFork = pindex->pprev;
638 // check level 4: check whether spent txouts were spent within the main chain
641 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
645 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
646 if (!mapBlockPos.count(posFind))
648 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
649 pindexFork = pindex->pprev;
651 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
654 CTransaction txSpend;
655 if (!txSpend.ReadFromDisk(txpos))
657 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
658 pindexFork = pindex->pprev;
660 else if (!txSpend.CheckTransaction())
662 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
663 pindexFork = pindex->pprev;
668 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
669 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
673 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
674 pindexFork = pindex->pprev;
682 // check level 5: check whether all prevouts are marked spent
684 BOOST_FOREACH(const CTxIn &txin, tx.vin)
687 if (ReadTxIndex(txin.prevout.hash, txindex))
688 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
690 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
691 pindexFork = pindex->pprev;
699 // Reorg back to the fork
700 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
702 if (!block.ReadFromDisk(pindexFork))
703 return error("LoadBlockIndex() : block.ReadFromDisk failed");
705 block.SetBestChain(txdb, pindexFork);
719 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
721 return Write(string("addrman"), addrman);
724 bool CAddrDB::LoadAddresses()
726 if (Read(string("addrman"), addrman))
728 printf("Loaded %i addresses\n", addrman.size());
732 // Read pre-0.6 addr records
734 vector<CAddress> vAddr;
735 vector<vector<unsigned char> > vDelete;
738 Dbc* pcursor = GetCursor();
747 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
748 if (ret == DB_NOTFOUND)
756 if (strType == "addr")
760 vAddr.push_back(addr);
765 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
766 printf("Loaded %i addresses\n", addrman.size());
768 // Note: old records left; we ran into hangs-on-startup
769 // bugs for some users who (we think) were running after
770 // an unclean shutdown.
777 return CAddrDB("cr+").LoadAddresses();
787 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
790 return Write(make_pair(string("name"), strAddress), strName);
793 bool CWalletDB::EraseName(const string& strAddress)
795 // This should only be used for sending addresses, never for receiving addresses,
796 // receiving addresses must always have an address book entry if they're not change return.
798 return Erase(make_pair(string("name"), strAddress));
801 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
804 return Read(make_pair(string("acc"), strAccount), account);
807 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
809 return Write(make_pair(string("acc"), strAccount), account);
812 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
814 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
817 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
819 list<CAccountingEntry> entries;
820 ListAccountCreditDebit(strAccount, entries);
822 int64 nCreditDebit = 0;
823 BOOST_FOREACH (const CAccountingEntry& entry, entries)
824 nCreditDebit += entry.nCreditDebit;
829 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
831 bool fAllAccounts = (strAccount == "*");
833 Dbc* pcursor = GetCursor();
835 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
836 unsigned int fFlags = DB_SET_RANGE;
841 if (fFlags == DB_SET_RANGE)
842 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
844 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
846 if (ret == DB_NOTFOUND)
851 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
857 if (strType != "acentry")
859 CAccountingEntry acentry;
860 ssKey >> acentry.strAccount;
861 if (!fAllAccounts && acentry.strAccount != strAccount)
865 entries.push_back(acentry);
872 int CWalletDB::LoadWallet(CWallet* pwallet)
874 pwallet->vchDefaultKey.clear();
875 int nFileVersion = 0;
876 vector<uint256> vWalletUpgrade;
877 bool fIsEncrypted = false;
879 //// todo: shouldn't we catch exceptions and try to recover and continue?
880 CRITICAL_BLOCK(pwallet->cs_wallet)
883 if (Read((string)"minversion", nMinVersion))
885 if (nMinVersion > CLIENT_VERSION)
887 pwallet->LoadMinVersion(nMinVersion);
891 Dbc* pcursor = GetCursor();
894 printf("Error getting wallet database cursor\n");
903 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
904 if (ret == DB_NOTFOUND)
908 printf("Error reading next record from wallet database\n");
913 // Taking advantage of the fact that pair serialization
914 // is just the two items serialized one after the other
917 if (strType == "name")
921 ssValue >> pwallet->mapAddressBook[strAddress];
923 else if (strType == "tx")
927 CWalletTx& wtx = pwallet->mapWallet[hash];
929 wtx.BindWallet(pwallet);
931 if (wtx.GetHash() != hash)
932 printf("Error in wallet.dat, hash mismatch\n");
934 // Undo serialize changes in 31600
935 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
937 if (!ssValue.empty())
941 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
942 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
943 wtx.fTimeReceivedIsTxTime = fTmp;
947 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
948 wtx.fTimeReceivedIsTxTime = 0;
950 vWalletUpgrade.push_back(hash);
954 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
955 //printf(" %12I64d %s %s %s\n",
956 // wtx.vout[0].nValue,
957 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
958 // wtx.hashBlock.ToString().substr(0,20).c_str(),
959 // wtx.mapValue["message"].c_str());
961 else if (strType == "acentry")
967 if (nNumber > nAccountingEntryNumber)
968 nAccountingEntryNumber = nNumber;
970 else if (strType == "key" || strType == "wkey")
972 vector<unsigned char> vchPubKey;
975 if (strType == "key")
979 key.SetPubKey(vchPubKey);
980 key.SetPrivKey(pkey);
981 if (key.GetPubKey() != vchPubKey)
983 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
988 printf("Error reading wallet database: invalid CPrivKey\n");
996 key.SetPubKey(vchPubKey);
997 key.SetPrivKey(wkey.vchPrivKey);
998 if (key.GetPubKey() != vchPubKey)
1000 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1005 printf("Error reading wallet database: invalid CWalletKey\n");
1009 if (!pwallet->LoadKey(key))
1011 printf("Error reading wallet database: LoadKey failed\n");
1015 else if (strType == "mkey")
1019 CMasterKey kMasterKey;
1020 ssValue >> kMasterKey;
1021 if(pwallet->mapMasterKeys.count(nID) != 0)
1023 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1026 pwallet->mapMasterKeys[nID] = kMasterKey;
1027 if (pwallet->nMasterKeyMaxID < nID)
1028 pwallet->nMasterKeyMaxID = nID;
1030 else if (strType == "ckey")
1032 vector<unsigned char> vchPubKey;
1034 vector<unsigned char> vchPrivKey;
1035 ssValue >> vchPrivKey;
1036 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1038 printf("Error reading wallet database: LoadCryptedKey failed\n");
1041 fIsEncrypted = true;
1043 else if (strType == "defaultkey")
1045 ssValue >> pwallet->vchDefaultKey;
1047 else if (strType == "pool")
1051 pwallet->setKeyPool.insert(nIndex);
1053 else if (strType == "version")
1055 ssValue >> nFileVersion;
1056 if (nFileVersion == 10300)
1059 else if (strType == "cscript")
1065 if (!pwallet->LoadCScript(script))
1067 printf("Error reading wallet database: LoadCScript failed\n");
1075 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1076 WriteTx(hash, pwallet->mapWallet[hash]);
1078 printf("nFileVersion = %d\n", nFileVersion);
1081 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1082 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1083 return DB_NEED_REWRITE;
1085 if (nFileVersion < CLIENT_VERSION) // Update
1087 // Get rid of old debug.log file in current directory
1088 if (nFileVersion <= 105 && !pszSetDataDir[0])
1089 unlink("debug.log");
1091 WriteVersion(CLIENT_VERSION);
1097 void ThreadFlushWalletDB(void* parg)
1099 const string& strFile = ((const string*)parg)[0];
1100 static bool fOneThread;
1104 if (!GetBoolArg("-flushwallet", true))
1107 unsigned int nLastSeen = nWalletDBUpdated;
1108 unsigned int nLastFlushed = nWalletDBUpdated;
1109 int64 nLastWalletUpdate = GetTime();
1114 if (nLastSeen != nWalletDBUpdated)
1116 nLastSeen = nWalletDBUpdated;
1117 nLastWalletUpdate = GetTime();
1120 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1122 TRY_CRITICAL_BLOCK(cs_db)
1124 // Don't do this if any databases are in use
1126 map<string, int>::iterator mi = mapFileUseCount.begin();
1127 while (mi != mapFileUseCount.end())
1129 nRefCount += (*mi).second;
1133 if (nRefCount == 0 && !fShutdown)
1135 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1136 if (mi != mapFileUseCount.end())
1138 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1139 printf("Flushing wallet.dat\n");
1140 nLastFlushed = nWalletDBUpdated;
1141 int64 nStart = GetTimeMillis();
1143 // Flush wallet.dat so it's self contained
1145 dbenv.txn_checkpoint(0, 0, 0);
1146 dbenv.lsn_reset(strFile.c_str(), 0);
1148 mapFileUseCount.erase(mi++);
1149 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1157 bool BackupWallet(const CWallet& wallet, const string& strDest)
1159 if (!wallet.fFileBacked)
1163 CRITICAL_BLOCK(cs_db)
1165 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1167 // Flush log data to the dat file
1168 CloseDb(wallet.strWalletFile);
1169 dbenv.txn_checkpoint(0, 0, 0);
1170 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1171 mapFileUseCount.erase(wallet.strWalletFile);
1174 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1175 filesystem::path pathDest(strDest);
1176 if (filesystem::is_directory(pathDest))
1177 pathDest = pathDest / wallet.strWalletFile;
1180 #if BOOST_VERSION >= 104000
1181 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1183 filesystem::copy_file(pathSrc, pathDest);
1185 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1187 } catch(const filesystem::filesystem_error &e) {
1188 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());