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" && IsInitialBlockDownload())
168 dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
172 --mapFileUseCount[strFile];
176 void static CloseDb(const string& strFile)
180 if (mapDb[strFile] != NULL)
182 // Close the database handle
183 Db* pdb = mapDb[strFile];
186 mapDb[strFile] = NULL;
191 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
197 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
199 // Flush log data to the dat file
201 dbenv.txn_checkpoint(0, 0, 0);
202 dbenv.lsn_reset(strFile.c_str(), 0);
203 mapFileUseCount.erase(strFile);
205 bool fSuccess = true;
206 printf("Rewriting %s...\n", strFile.c_str());
207 string strFileRes = strFile + ".rewrite";
208 { // surround usage of db with extra {}
209 CDB db(strFile.c_str(), "r");
210 Db* pdbCopy = new Db(&dbenv, 0);
212 int ret = pdbCopy->open(NULL, // Txn pointer
213 strFileRes.c_str(), // Filename
214 "main", // Logical db name
215 DB_BTREE, // Database type
220 printf("Cannot create database file %s\n", strFileRes.c_str());
224 Dbc* pcursor = db.GetCursor();
230 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
231 if (ret == DB_NOTFOUND)
243 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
245 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
249 ssValue << CLIENT_VERSION;
251 Dbt datKey(&ssKey[0], ssKey.size());
252 Dbt datValue(&ssValue[0], ssValue.size());
253 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
261 if (pdbCopy->close(0))
269 if (dbA.remove(strFile.c_str(), NULL, 0))
272 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
276 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
286 void DBFlush(bool fShutdown)
288 // Flush log data to the actual data file
289 // on all files that are not in use
290 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
295 map<string, int>::iterator mi = mapFileUseCount.begin();
296 while (mi != mapFileUseCount.end())
298 string strFile = (*mi).first;
299 int nRefCount = (*mi).second;
300 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
303 // Move log data to the dat file
305 dbenv.txn_checkpoint(0, 0, 0);
306 printf("%s flush\n", strFile.c_str());
307 dbenv.lsn_reset(strFile.c_str(), 0);
308 mapFileUseCount.erase(mi++);
316 if (mapFileUseCount.empty())
318 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
334 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
338 return Read(make_pair(string("tx"), hash), txindex);
341 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
344 return Write(make_pair(string("tx"), hash), txindex);
347 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
352 uint256 hash = tx.GetHash();
353 CTxIndex txindex(pos, tx.vout.size());
354 return Write(make_pair(string("tx"), hash), txindex);
357 bool CTxDB::EraseTxIndex(const CTransaction& tx)
360 uint256 hash = tx.GetHash();
362 return Erase(make_pair(string("tx"), hash));
365 bool CTxDB::ContainsTx(uint256 hash)
368 return Exists(make_pair(string("tx"), hash));
371 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
377 Dbc* pcursor = GetCursor();
381 unsigned int fFlags = DB_SET_RANGE;
386 if (fFlags == DB_SET_RANGE)
387 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
389 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
391 if (ret == DB_NOTFOUND)
403 ssKey >> strType >> hashItem >> pos;
405 ssValue >> nItemHeight;
408 if (strType != "owner" || hashItem != hash160)
410 if (nItemHeight >= nMinHeight)
412 vtx.resize(vtx.size()+1);
413 if (!vtx.back().ReadFromDisk(pos))
425 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
429 if (!ReadTxIndex(hash, txindex))
431 return (tx.ReadFromDisk(txindex.pos));
434 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
437 return ReadDiskTx(hash, tx, txindex);
440 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
442 return ReadDiskTx(outpoint.hash, tx, txindex);
445 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
448 return ReadDiskTx(outpoint.hash, tx, txindex);
451 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
453 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
456 bool CTxDB::EraseBlockIndex(uint256 hash)
458 return Erase(make_pair(string("blockindex"), hash));
461 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
463 return Read(string("hashBestChain"), hashBestChain);
466 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
468 return Write(string("hashBestChain"), hashBestChain);
471 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
473 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
476 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
478 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
481 CBlockIndex static * InsertBlockIndex(uint256 hash)
487 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
488 if (mi != mapBlockIndex.end())
492 CBlockIndex* pindexNew = new CBlockIndex();
494 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
495 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
496 pindexNew->phashBlock = &((*mi).first);
501 bool CTxDB::LoadBlockIndex()
503 // Get database cursor
504 Dbc* pcursor = GetCursor();
508 // Load mapBlockIndex
509 unsigned int fFlags = DB_SET_RANGE;
514 if (fFlags == DB_SET_RANGE)
515 ssKey << make_pair(string("blockindex"), uint256(0));
517 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
519 if (ret == DB_NOTFOUND)
527 if (strType == "blockindex")
529 CDiskBlockIndex diskindex;
530 ssValue >> diskindex;
532 // Construct block index object
533 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
534 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
535 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
536 pindexNew->nFile = diskindex.nFile;
537 pindexNew->nBlockPos = diskindex.nBlockPos;
538 pindexNew->nHeight = diskindex.nHeight;
539 pindexNew->nVersion = diskindex.nVersion;
540 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
541 pindexNew->nTime = diskindex.nTime;
542 pindexNew->nBits = diskindex.nBits;
543 pindexNew->nNonce = diskindex.nNonce;
545 // Watch for genesis block
546 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
547 pindexGenesisBlock = pindexNew;
549 if (!pindexNew->CheckIndex())
550 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
559 // Calculate bnChainWork
560 vector<pair<int, CBlockIndex*> > vSortedByHeight;
561 vSortedByHeight.reserve(mapBlockIndex.size());
562 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
564 CBlockIndex* pindex = item.second;
565 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
567 sort(vSortedByHeight.begin(), vSortedByHeight.end());
568 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
570 CBlockIndex* pindex = item.second;
571 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
574 // Load hashBestChain pointer to end of best chain
575 if (!ReadHashBestChain(hashBestChain))
577 if (pindexGenesisBlock == NULL)
579 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
581 if (!mapBlockIndex.count(hashBestChain))
582 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
583 pindexBest = mapBlockIndex[hashBestChain];
584 nBestHeight = pindexBest->nHeight;
585 bnBestChainWork = pindexBest->bnChainWork;
586 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
588 // Load bnBestInvalidWork, OK if it doesn't exist
589 ReadBestInvalidWork(bnBestInvalidWork);
591 // Verify blocks in the best chain
592 int nCheckLevel = GetArg("-checklevel", 1);
593 int nCheckDepth = GetArg( "-checkblocks", 2500);
594 if (nCheckDepth == 0)
595 nCheckDepth = 1000000000; // suffices until the year 19000
596 if (nCheckDepth > nBestHeight)
597 nCheckDepth = nBestHeight;
598 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
599 CBlockIndex* pindexFork = NULL;
600 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
601 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
603 if (pindex->nHeight < nBestHeight-nCheckDepth)
606 if (!block.ReadFromDisk(pindex))
607 return error("LoadBlockIndex() : block.ReadFromDisk failed");
608 // check level 1: verify block validity
609 if (nCheckLevel>0 && !block.CheckBlock())
611 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
612 pindexFork = pindex->pprev;
614 // check level 2: verify transaction index validity
617 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
618 mapBlockPos[pos] = pindex;
619 BOOST_FOREACH(const CTransaction &tx, block.vtx)
621 uint256 hashTx = tx.GetHash();
623 if (ReadTxIndex(hashTx, txindex))
625 // check level 3: checker transaction hashes
626 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
628 // either an error or a duplicate transaction
629 CTransaction txFound;
630 if (!txFound.ReadFromDisk(txindex.pos))
632 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
633 pindexFork = pindex->pprev;
636 if (txFound.GetHash() != hashTx) // not a duplicate tx
638 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
639 pindexFork = pindex->pprev;
642 // check level 4: check whether spent txouts were spent within the main chain
645 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
649 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
650 if (!mapBlockPos.count(posFind))
652 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
653 pindexFork = pindex->pprev;
655 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
658 CTransaction txSpend;
659 if (!txSpend.ReadFromDisk(txpos))
661 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
662 pindexFork = pindex->pprev;
664 else if (!txSpend.CheckTransaction())
666 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
667 pindexFork = pindex->pprev;
672 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
673 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
677 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
678 pindexFork = pindex->pprev;
686 // check level 5: check whether all prevouts are marked spent
688 BOOST_FOREACH(const CTxIn &txin, tx.vin)
691 if (ReadTxIndex(txin.prevout.hash, txindex))
692 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
694 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
695 pindexFork = pindex->pprev;
703 // Reorg back to the fork
704 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
706 if (!block.ReadFromDisk(pindexFork))
707 return error("LoadBlockIndex() : block.ReadFromDisk failed");
709 block.SetBestChain(txdb, pindexFork);
723 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
725 return Write(string("addrman"), addrman);
728 bool CAddrDB::LoadAddresses()
730 if (Read(string("addrman"), addrman))
732 printf("Loaded %i addresses\n", addrman.size());
736 // Read pre-0.6 addr records
738 vector<CAddress> vAddr;
739 vector<vector<unsigned char> > vDelete;
742 Dbc* pcursor = GetCursor();
751 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
752 if (ret == DB_NOTFOUND)
760 if (strType == "addr")
764 vAddr.push_back(addr);
769 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
770 printf("Loaded %i addresses\n", addrman.size());
772 // Note: old records left; we ran into hangs-on-startup
773 // bugs for some users who (we think) were running after
774 // an unclean shutdown.
781 return CAddrDB("cr+").LoadAddresses();
791 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
794 return Write(make_pair(string("name"), strAddress), strName);
797 bool CWalletDB::EraseName(const string& strAddress)
799 // This should only be used for sending addresses, never for receiving addresses,
800 // receiving addresses must always have an address book entry if they're not change return.
802 return Erase(make_pair(string("name"), strAddress));
805 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
808 return Read(make_pair(string("acc"), strAccount), account);
811 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
813 return Write(make_pair(string("acc"), strAccount), account);
816 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
818 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
821 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
823 list<CAccountingEntry> entries;
824 ListAccountCreditDebit(strAccount, entries);
826 int64 nCreditDebit = 0;
827 BOOST_FOREACH (const CAccountingEntry& entry, entries)
828 nCreditDebit += entry.nCreditDebit;
833 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
835 bool fAllAccounts = (strAccount == "*");
837 Dbc* pcursor = GetCursor();
839 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
840 unsigned int fFlags = DB_SET_RANGE;
845 if (fFlags == DB_SET_RANGE)
846 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
848 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
850 if (ret == DB_NOTFOUND)
855 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
861 if (strType != "acentry")
863 CAccountingEntry acentry;
864 ssKey >> acentry.strAccount;
865 if (!fAllAccounts && acentry.strAccount != strAccount)
869 entries.push_back(acentry);
876 int CWalletDB::LoadWallet(CWallet* pwallet)
878 pwallet->vchDefaultKey.clear();
879 int nFileVersion = 0;
880 vector<uint256> vWalletUpgrade;
881 bool fIsEncrypted = false;
883 //// todo: shouldn't we catch exceptions and try to recover and continue?
885 LOCK(pwallet->cs_wallet);
887 if (Read((string)"minversion", nMinVersion))
889 if (nMinVersion > CLIENT_VERSION)
891 pwallet->LoadMinVersion(nMinVersion);
895 Dbc* pcursor = GetCursor();
898 printf("Error getting wallet database cursor\n");
907 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
908 if (ret == DB_NOTFOUND)
912 printf("Error reading next record from wallet database\n");
917 // Taking advantage of the fact that pair serialization
918 // is just the two items serialized one after the other
921 if (strType == "name")
925 ssValue >> pwallet->mapAddressBook[strAddress];
927 else if (strType == "tx")
931 CWalletTx& wtx = pwallet->mapWallet[hash];
933 wtx.BindWallet(pwallet);
935 if (wtx.GetHash() != hash)
936 printf("Error in wallet.dat, hash mismatch\n");
938 // Undo serialize changes in 31600
939 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
941 if (!ssValue.empty())
945 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
946 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
947 wtx.fTimeReceivedIsTxTime = fTmp;
951 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
952 wtx.fTimeReceivedIsTxTime = 0;
954 vWalletUpgrade.push_back(hash);
958 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
959 //printf(" %12I64d %s %s %s\n",
960 // wtx.vout[0].nValue,
961 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
962 // wtx.hashBlock.ToString().substr(0,20).c_str(),
963 // wtx.mapValue["message"].c_str());
965 else if (strType == "acentry")
971 if (nNumber > nAccountingEntryNumber)
972 nAccountingEntryNumber = nNumber;
974 else if (strType == "key" || strType == "wkey")
976 vector<unsigned char> vchPubKey;
979 if (strType == "key")
983 key.SetPubKey(vchPubKey);
984 key.SetPrivKey(pkey);
985 if (key.GetPubKey() != vchPubKey)
987 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
992 printf("Error reading wallet database: invalid CPrivKey\n");
1000 key.SetPubKey(vchPubKey);
1001 key.SetPrivKey(wkey.vchPrivKey);
1002 if (key.GetPubKey() != vchPubKey)
1004 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1009 printf("Error reading wallet database: invalid CWalletKey\n");
1013 if (!pwallet->LoadKey(key))
1015 printf("Error reading wallet database: LoadKey failed\n");
1019 else if (strType == "mkey")
1023 CMasterKey kMasterKey;
1024 ssValue >> kMasterKey;
1025 if(pwallet->mapMasterKeys.count(nID) != 0)
1027 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1030 pwallet->mapMasterKeys[nID] = kMasterKey;
1031 if (pwallet->nMasterKeyMaxID < nID)
1032 pwallet->nMasterKeyMaxID = nID;
1034 else if (strType == "ckey")
1036 vector<unsigned char> vchPubKey;
1038 vector<unsigned char> vchPrivKey;
1039 ssValue >> vchPrivKey;
1040 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1042 printf("Error reading wallet database: LoadCryptedKey failed\n");
1045 fIsEncrypted = true;
1047 else if (strType == "defaultkey")
1049 ssValue >> pwallet->vchDefaultKey;
1051 else if (strType == "pool")
1055 pwallet->setKeyPool.insert(nIndex);
1057 else if (strType == "version")
1059 ssValue >> nFileVersion;
1060 if (nFileVersion == 10300)
1063 else if (strType == "cscript")
1069 if (!pwallet->LoadCScript(script))
1071 printf("Error reading wallet database: LoadCScript failed\n");
1079 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1080 WriteTx(hash, pwallet->mapWallet[hash]);
1082 printf("nFileVersion = %d\n", nFileVersion);
1085 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1086 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1087 return DB_NEED_REWRITE;
1089 if (nFileVersion < CLIENT_VERSION) // Update
1090 WriteVersion(CLIENT_VERSION);
1095 void ThreadFlushWalletDB(void* parg)
1097 const string& strFile = ((const string*)parg)[0];
1098 static bool fOneThread;
1102 if (!GetBoolArg("-flushwallet", true))
1105 unsigned int nLastSeen = nWalletDBUpdated;
1106 unsigned int nLastFlushed = nWalletDBUpdated;
1107 int64 nLastWalletUpdate = GetTime();
1112 if (nLastSeen != nWalletDBUpdated)
1114 nLastSeen = nWalletDBUpdated;
1115 nLastWalletUpdate = GetTime();
1118 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1120 TRY_LOCK(cs_db,lockDb);
1123 // Don't do this if any databases are in use
1125 map<string, int>::iterator mi = mapFileUseCount.begin();
1126 while (mi != mapFileUseCount.end())
1128 nRefCount += (*mi).second;
1132 if (nRefCount == 0 && !fShutdown)
1134 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1135 if (mi != mapFileUseCount.end())
1137 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1138 printf("Flushing wallet.dat\n");
1139 nLastFlushed = nWalletDBUpdated;
1140 int64 nStart = GetTimeMillis();
1142 // Flush wallet.dat so it's self contained
1144 dbenv.txn_checkpoint(0, 0, 0);
1145 dbenv.lsn_reset(strFile.c_str(), 0);
1147 mapFileUseCount.erase(mi++);
1148 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1156 bool BackupWallet(const CWallet& wallet, const string& strDest)
1158 if (!wallet.fFileBacked)
1164 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1166 // Flush log data to the dat file
1167 CloseDb(wallet.strWalletFile);
1168 dbenv.txn_checkpoint(0, 0, 0);
1169 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1170 mapFileUseCount.erase(wallet.strWalletFile);
1173 filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
1174 filesystem::path pathDest(strDest);
1175 if (filesystem::is_directory(pathDest))
1176 pathDest /= wallet.strWalletFile;
1179 #if BOOST_VERSION >= 104000
1180 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1182 filesystem::copy_file(pathSrc, pathDest);
1184 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1186 } catch(const filesystem::filesystem_error &e) {
1187 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());