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() && nBestHeight % 5000 != 0)
165 dbenv.txn_checkpoint(0, nMinutes, 0);
167 CRITICAL_BLOCK(cs_db)
168 --mapFileUseCount[strFile];
171 void static CloseDb(const string& strFile)
173 CRITICAL_BLOCK(cs_db)
175 if (mapDb[strFile] != NULL)
177 // Close the database handle
178 Db* pdb = mapDb[strFile];
181 mapDb[strFile] = NULL;
186 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
190 CRITICAL_BLOCK(cs_db)
192 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
194 // Flush log data to the dat file
196 dbenv.txn_checkpoint(0, 0, 0);
197 dbenv.lsn_reset(strFile.c_str(), 0);
198 mapFileUseCount.erase(strFile);
200 bool fSuccess = true;
201 printf("Rewriting %s...\n", strFile.c_str());
202 string strFileRes = strFile + ".rewrite";
203 { // surround usage of db with extra {}
204 CDB db(strFile.c_str(), "r");
205 Db* pdbCopy = new Db(&dbenv, 0);
207 int ret = pdbCopy->open(NULL, // Txn pointer
208 strFileRes.c_str(), // Filename
209 "main", // Logical db name
210 DB_BTREE, // Database type
215 printf("Cannot create database file %s\n", strFileRes.c_str());
219 Dbc* pcursor = db.GetCursor();
225 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
226 if (ret == DB_NOTFOUND)
238 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
240 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
244 ssValue << CLIENT_VERSION;
246 Dbt datKey(&ssKey[0], ssKey.size());
247 Dbt datValue(&ssValue[0], ssValue.size());
248 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
256 if (pdbCopy->close(0))
264 if (dbA.remove(strFile.c_str(), NULL, 0))
267 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
271 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
281 void DBFlush(bool fShutdown)
283 // Flush log data to the actual data file
284 // on all files that are not in use
285 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
288 CRITICAL_BLOCK(cs_db)
290 map<string, int>::iterator mi = mapFileUseCount.begin();
291 while (mi != mapFileUseCount.end())
293 string strFile = (*mi).first;
294 int nRefCount = (*mi).second;
295 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
298 // Move log data to the dat file
300 dbenv.txn_checkpoint(0, 0, 0);
301 printf("%s flush\n", strFile.c_str());
302 dbenv.lsn_reset(strFile.c_str(), 0);
303 mapFileUseCount.erase(mi++);
311 if (mapFileUseCount.empty())
313 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
329 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
333 return Read(make_pair(string("tx"), hash), txindex);
336 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
339 return Write(make_pair(string("tx"), hash), txindex);
342 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
347 uint256 hash = tx.GetHash();
348 CTxIndex txindex(pos, tx.vout.size());
349 return Write(make_pair(string("tx"), hash), txindex);
352 bool CTxDB::EraseTxIndex(const CTransaction& tx)
355 uint256 hash = tx.GetHash();
357 return Erase(make_pair(string("tx"), hash));
360 bool CTxDB::ContainsTx(uint256 hash)
363 return Exists(make_pair(string("tx"), hash));
366 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
372 Dbc* pcursor = GetCursor();
376 unsigned int fFlags = DB_SET_RANGE;
381 if (fFlags == DB_SET_RANGE)
382 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
384 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
386 if (ret == DB_NOTFOUND)
398 ssKey >> strType >> hashItem >> pos;
400 ssValue >> nItemHeight;
403 if (strType != "owner" || hashItem != hash160)
405 if (nItemHeight >= nMinHeight)
407 vtx.resize(vtx.size()+1);
408 if (!vtx.back().ReadFromDisk(pos))
420 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
424 if (!ReadTxIndex(hash, txindex))
426 return (tx.ReadFromDisk(txindex.pos));
429 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
432 return ReadDiskTx(hash, tx, txindex);
435 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
437 return ReadDiskTx(outpoint.hash, tx, txindex);
440 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
443 return ReadDiskTx(outpoint.hash, tx, txindex);
446 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
448 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
451 bool CTxDB::EraseBlockIndex(uint256 hash)
453 return Erase(make_pair(string("blockindex"), hash));
456 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
458 return Read(string("hashBestChain"), hashBestChain);
461 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
463 return Write(string("hashBestChain"), hashBestChain);
466 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
468 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
471 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
473 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
476 CBlockIndex static * InsertBlockIndex(uint256 hash)
482 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
483 if (mi != mapBlockIndex.end())
487 CBlockIndex* pindexNew = new CBlockIndex();
489 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
490 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
491 pindexNew->phashBlock = &((*mi).first);
496 bool CTxDB::LoadBlockIndex()
498 // Get database cursor
499 Dbc* pcursor = GetCursor();
503 // Load mapBlockIndex
504 unsigned int fFlags = DB_SET_RANGE;
509 if (fFlags == DB_SET_RANGE)
510 ssKey << make_pair(string("blockindex"), uint256(0));
512 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
514 if (ret == DB_NOTFOUND)
522 if (strType == "blockindex")
524 CDiskBlockIndex diskindex;
525 ssValue >> diskindex;
527 // Construct block index object
528 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
529 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
530 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
531 pindexNew->nFile = diskindex.nFile;
532 pindexNew->nBlockPos = diskindex.nBlockPos;
533 pindexNew->nHeight = diskindex.nHeight;
534 pindexNew->nVersion = diskindex.nVersion;
535 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
536 pindexNew->nTime = diskindex.nTime;
537 pindexNew->nBits = diskindex.nBits;
538 pindexNew->nNonce = diskindex.nNonce;
540 // Watch for genesis block
541 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
542 pindexGenesisBlock = pindexNew;
544 if (!pindexNew->CheckIndex())
545 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
554 // Calculate bnChainWork
555 vector<pair<int, CBlockIndex*> > vSortedByHeight;
556 vSortedByHeight.reserve(mapBlockIndex.size());
557 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
559 CBlockIndex* pindex = item.second;
560 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
562 sort(vSortedByHeight.begin(), vSortedByHeight.end());
563 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
565 CBlockIndex* pindex = item.second;
566 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
569 // Load hashBestChain pointer to end of best chain
570 if (!ReadHashBestChain(hashBestChain))
572 if (pindexGenesisBlock == NULL)
574 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
576 if (!mapBlockIndex.count(hashBestChain))
577 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
578 pindexBest = mapBlockIndex[hashBestChain];
579 nBestHeight = pindexBest->nHeight;
580 bnBestChainWork = pindexBest->bnChainWork;
581 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
583 // Load bnBestInvalidWork, OK if it doesn't exist
584 ReadBestInvalidWork(bnBestInvalidWork);
586 // Verify blocks in the best chain
587 int nCheckLevel = GetArg("-checklevel", 1);
588 int nCheckDepth = GetArg( "-checkblocks", 2500);
589 if (nCheckDepth == 0)
590 nCheckDepth = 1000000000; // suffices until the year 19000
591 if (nCheckDepth > nBestHeight)
592 nCheckDepth = nBestHeight;
593 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
594 CBlockIndex* pindexFork = NULL;
595 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
596 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
598 if (pindex->nHeight < nBestHeight-nCheckDepth)
601 if (!block.ReadFromDisk(pindex))
602 return error("LoadBlockIndex() : block.ReadFromDisk failed");
603 // check level 1: verify block validity
604 if (nCheckLevel>0 && !block.CheckBlock())
606 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
607 pindexFork = pindex->pprev;
609 // check level 2: verify transaction index validity
612 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
613 mapBlockPos[pos] = pindex;
614 BOOST_FOREACH(const CTransaction &tx, block.vtx)
616 uint256 hashTx = tx.GetHash();
618 if (ReadTxIndex(hashTx, txindex))
620 // check level 3: checker transaction hashes
621 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
623 // either an error or a duplicate transaction
624 CTransaction txFound;
625 if (!txFound.ReadFromDisk(txindex.pos))
627 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
628 pindexFork = pindex->pprev;
631 if (txFound.GetHash() != hashTx) // not a duplicate tx
633 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
634 pindexFork = pindex->pprev;
637 // check level 4: check whether spent txouts were spent within the main chain
640 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
644 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
645 if (!mapBlockPos.count(posFind))
647 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
648 pindexFork = pindex->pprev;
650 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
653 CTransaction txSpend;
654 if (!txSpend.ReadFromDisk(txpos))
656 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
657 pindexFork = pindex->pprev;
659 else if (!txSpend.CheckTransaction())
661 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
662 pindexFork = pindex->pprev;
667 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
668 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
672 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
673 pindexFork = pindex->pprev;
681 // check level 5: check whether all prevouts are marked spent
683 BOOST_FOREACH(const CTxIn &txin, tx.vin)
686 if (ReadTxIndex(txin.prevout.hash, txindex))
687 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
689 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
690 pindexFork = pindex->pprev;
698 // Reorg back to the fork
699 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
701 if (!block.ReadFromDisk(pindexFork))
702 return error("LoadBlockIndex() : block.ReadFromDisk failed");
704 block.SetBestChain(txdb, pindexFork);
718 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
720 return Write(string("addrman"), addrman);
723 bool CAddrDB::LoadAddresses()
725 bool fAddrMan = false;
726 if (Read(string("addrman"), addrman))
728 printf("Loaded %i addresses\n", addrman.size());
732 vector<CAddress> vAddr;
733 vector<vector<unsigned char> > vDelete;
736 Dbc* pcursor = GetCursor();
745 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
746 if (ret == DB_NOTFOUND)
754 if (strType == "addr")
758 vector<unsigned char> vchKey;
760 vDelete.push_back(vchKey);
766 vAddr.push_back(addr);
773 BOOST_FOREACH(const vector<unsigned char> &vchKey, vDelete)
774 Erase(make_pair(string("addr"), vchKey));
778 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
779 printf("Loaded %i addresses\n", addrman.size());
787 return CAddrDB("cr+").LoadAddresses();
797 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
800 return Write(make_pair(string("name"), strAddress), strName);
803 bool CWalletDB::EraseName(const string& strAddress)
805 // This should only be used for sending addresses, never for receiving addresses,
806 // receiving addresses must always have an address book entry if they're not change return.
808 return Erase(make_pair(string("name"), strAddress));
811 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
814 return Read(make_pair(string("acc"), strAccount), account);
817 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
819 return Write(make_pair(string("acc"), strAccount), account);
822 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
824 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
827 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
829 list<CAccountingEntry> entries;
830 ListAccountCreditDebit(strAccount, entries);
832 int64 nCreditDebit = 0;
833 BOOST_FOREACH (const CAccountingEntry& entry, entries)
834 nCreditDebit += entry.nCreditDebit;
839 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
841 bool fAllAccounts = (strAccount == "*");
843 Dbc* pcursor = GetCursor();
845 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
846 unsigned int fFlags = DB_SET_RANGE;
851 if (fFlags == DB_SET_RANGE)
852 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
854 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
856 if (ret == DB_NOTFOUND)
861 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
867 if (strType != "acentry")
869 CAccountingEntry acentry;
870 ssKey >> acentry.strAccount;
871 if (!fAllAccounts && acentry.strAccount != strAccount)
875 entries.push_back(acentry);
882 int CWalletDB::LoadWallet(CWallet* pwallet)
884 pwallet->vchDefaultKey.clear();
885 int nFileVersion = 0;
886 vector<uint256> vWalletUpgrade;
887 bool fIsEncrypted = false;
889 //// todo: shouldn't we catch exceptions and try to recover and continue?
890 CRITICAL_BLOCK(pwallet->cs_wallet)
893 if (Read((string)"minversion", nMinVersion))
895 if (nMinVersion > CLIENT_VERSION)
897 pwallet->LoadMinVersion(nMinVersion);
901 Dbc* pcursor = GetCursor();
904 printf("Error getting wallet database cursor\n");
913 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
914 if (ret == DB_NOTFOUND)
918 printf("Error reading next record from wallet database\n");
923 // Taking advantage of the fact that pair serialization
924 // is just the two items serialized one after the other
927 if (strType == "name")
931 ssValue >> pwallet->mapAddressBook[strAddress];
933 else if (strType == "tx")
937 CWalletTx& wtx = pwallet->mapWallet[hash];
939 wtx.BindWallet(pwallet);
941 if (wtx.GetHash() != hash)
942 printf("Error in wallet.dat, hash mismatch\n");
944 // Undo serialize changes in 31600
945 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
947 if (!ssValue.empty())
951 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
952 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
953 wtx.fTimeReceivedIsTxTime = fTmp;
957 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
958 wtx.fTimeReceivedIsTxTime = 0;
960 vWalletUpgrade.push_back(hash);
964 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
965 //printf(" %12I64d %s %s %s\n",
966 // wtx.vout[0].nValue,
967 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
968 // wtx.hashBlock.ToString().substr(0,20).c_str(),
969 // wtx.mapValue["message"].c_str());
971 else if (strType == "acentry")
977 if (nNumber > nAccountingEntryNumber)
978 nAccountingEntryNumber = nNumber;
980 else if (strType == "key" || strType == "wkey")
982 vector<unsigned char> vchPubKey;
985 if (strType == "key")
989 key.SetPubKey(vchPubKey);
990 key.SetPrivKey(pkey);
991 if (key.GetPubKey() != vchPubKey)
993 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
998 printf("Error reading wallet database: invalid CPrivKey\n");
1006 key.SetPubKey(vchPubKey);
1007 key.SetPrivKey(wkey.vchPrivKey);
1008 if (key.GetPubKey() != vchPubKey)
1010 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1015 printf("Error reading wallet database: invalid CWalletKey\n");
1019 if (!pwallet->LoadKey(key))
1021 printf("Error reading wallet database: LoadKey failed\n");
1025 else if (strType == "mkey")
1029 CMasterKey kMasterKey;
1030 ssValue >> kMasterKey;
1031 if(pwallet->mapMasterKeys.count(nID) != 0)
1033 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1036 pwallet->mapMasterKeys[nID] = kMasterKey;
1037 if (pwallet->nMasterKeyMaxID < nID)
1038 pwallet->nMasterKeyMaxID = nID;
1040 else if (strType == "ckey")
1042 vector<unsigned char> vchPubKey;
1044 vector<unsigned char> vchPrivKey;
1045 ssValue >> vchPrivKey;
1046 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1048 printf("Error reading wallet database: LoadCryptedKey failed\n");
1051 fIsEncrypted = true;
1053 else if (strType == "defaultkey")
1055 ssValue >> pwallet->vchDefaultKey;
1057 else if (strType == "pool")
1061 pwallet->setKeyPool.insert(nIndex);
1063 else if (strType == "version")
1065 ssValue >> nFileVersion;
1066 if (nFileVersion == 10300)
1069 else if (strType == "cscript")
1075 if (!pwallet->LoadCScript(script))
1077 printf("Error reading wallet database: LoadCScript failed\n");
1085 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1086 WriteTx(hash, pwallet->mapWallet[hash]);
1088 printf("nFileVersion = %d\n", nFileVersion);
1091 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1092 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1093 return DB_NEED_REWRITE;
1095 if (nFileVersion < CLIENT_VERSION) // Update
1097 // Get rid of old debug.log file in current directory
1098 if (nFileVersion <= 105 && !pszSetDataDir[0])
1099 unlink("debug.log");
1101 WriteVersion(CLIENT_VERSION);
1107 void ThreadFlushWalletDB(void* parg)
1109 const string& strFile = ((const string*)parg)[0];
1110 static bool fOneThread;
1114 if (!GetBoolArg("-flushwallet", true))
1117 unsigned int nLastSeen = nWalletDBUpdated;
1118 unsigned int nLastFlushed = nWalletDBUpdated;
1119 int64 nLastWalletUpdate = GetTime();
1124 if (nLastSeen != nWalletDBUpdated)
1126 nLastSeen = nWalletDBUpdated;
1127 nLastWalletUpdate = GetTime();
1130 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1132 TRY_CRITICAL_BLOCK(cs_db)
1134 // Don't do this if any databases are in use
1136 map<string, int>::iterator mi = mapFileUseCount.begin();
1137 while (mi != mapFileUseCount.end())
1139 nRefCount += (*mi).second;
1143 if (nRefCount == 0 && !fShutdown)
1145 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1146 if (mi != mapFileUseCount.end())
1148 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1149 printf("Flushing wallet.dat\n");
1150 nLastFlushed = nWalletDBUpdated;
1151 int64 nStart = GetTimeMillis();
1153 // Flush wallet.dat so it's self contained
1155 dbenv.txn_checkpoint(0, 0, 0);
1156 dbenv.lsn_reset(strFile.c_str(), 0);
1158 mapFileUseCount.erase(mi++);
1159 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1167 bool BackupWallet(const CWallet& wallet, const string& strDest)
1169 if (!wallet.fFileBacked)
1173 CRITICAL_BLOCK(cs_db)
1175 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1177 // Flush log data to the dat file
1178 CloseDb(wallet.strWalletFile);
1179 dbenv.txn_checkpoint(0, 0, 0);
1180 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1181 mapFileUseCount.erase(wallet.strWalletFile);
1184 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1185 filesystem::path pathDest(strDest);
1186 if (filesystem::is_directory(pathDest))
1187 pathDest = pathDest / wallet.strWalletFile;
1190 #if BOOST_VERSION >= 104000
1191 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1193 filesystem::copy_file(pathSrc, pathDest);
1195 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1197 } catch(const filesystem::filesystem_error &e) {
1198 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());