1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
9 #include <boost/version.hpp>
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
14 using namespace boost;
17 unsigned int nWalletDBUpdated;
18 uint64 nAccountingEntryNumber = 0;
26 static CCriticalSection cs_db;
27 static bool fDbEnvInit = false;
29 static map<string, int> mapFileUseCount;
30 static map<string, Db*> mapDb;
32 static void EnvShutdown()
42 catch (const DbException& e)
44 printf("EnvShutdown exception: %s (%d)\n", e.what(), e.get_errno());
46 DbEnv(0).remove(GetDataDir().c_str(), 0);
63 CDB::CDB(const char* pszFile, const char* pszMode) : pdb(NULL)
69 fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
70 bool fCreate = strchr(pszMode, 'c');
71 unsigned int nFlags = DB_THREAD;
81 string strDataDir = GetDataDir();
82 filesystem::path pathLogDir(strDataDir + "/database");
83 pathLogDir.make_preferred();
84 filesystem::create_directory(pathLogDir);
85 filesystem::path pathErrorFile(strDataDir + "/db.log");
86 pathErrorFile.make_preferred();
87 printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
89 int nDbCache = GetArg("-dbcache", 25);
90 dbenv.set_lg_dir(pathLogDir.string().c_str());
91 dbenv.set_cachesize(nDbCache / 1024, (nDbCache % 1024)*1048576, 1);
92 dbenv.set_lg_bsize(1048576);
93 dbenv.set_lg_max(10485760);
94 dbenv.set_lk_max_locks(10000);
95 dbenv.set_lk_max_objects(10000);
96 dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
97 dbenv.set_flags(DB_AUTO_COMMIT, 1);
98 dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
99 ret = dbenv.open(strDataDir.c_str(),
109 throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));
114 ++mapFileUseCount[strFile];
115 pdb = mapDb[strFile];
118 pdb = new Db(&dbenv, 0);
120 ret = pdb->open(NULL, // Txn pointer
122 "main", // Logical db name
123 DB_BTREE, // Database type
131 CRITICAL_BLOCK(cs_db)
132 --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);
170 CRITICAL_BLOCK(cs_db)
171 --mapFileUseCount[strFile];
174 void static CloseDb(const string& strFile)
176 CRITICAL_BLOCK(cs_db)
178 if (mapDb[strFile] != NULL)
180 // Close the database handle
181 Db* pdb = mapDb[strFile];
184 mapDb[strFile] = NULL;
189 bool CDB::Rewrite(const string& strFile, const char* pszSkip)
193 CRITICAL_BLOCK(cs_db)
195 if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
197 // Flush log data to the dat file
199 dbenv.txn_checkpoint(0, 0, 0);
200 dbenv.lsn_reset(strFile.c_str(), 0);
201 mapFileUseCount.erase(strFile);
203 bool fSuccess = true;
204 printf("Rewriting %s...\n", strFile.c_str());
205 string strFileRes = strFile + ".rewrite";
206 { // surround usage of db with extra {}
207 CDB db(strFile.c_str(), "r");
208 Db* pdbCopy = new Db(&dbenv, 0);
210 int ret = pdbCopy->open(NULL, // Txn pointer
211 strFileRes.c_str(), // Filename
212 "main", // Logical db name
213 DB_BTREE, // Database type
218 printf("Cannot create database file %s\n", strFileRes.c_str());
222 Dbc* pcursor = db.GetCursor();
228 int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
229 if (ret == DB_NOTFOUND)
241 strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
243 if (strncmp(&ssKey[0], "\x07version", 8) == 0)
247 ssValue << CLIENT_VERSION;
249 Dbt datKey(&ssKey[0], ssKey.size());
250 Dbt datValue(&ssValue[0], ssValue.size());
251 int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
259 if (pdbCopy->close(0))
267 if (dbA.remove(strFile.c_str(), NULL, 0))
270 if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
274 printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
284 void DBFlush(bool fShutdown)
286 // Flush log data to the actual data file
287 // on all files that are not in use
288 printf("DBFlush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
291 CRITICAL_BLOCK(cs_db)
293 map<string, int>::iterator mi = mapFileUseCount.begin();
294 while (mi != mapFileUseCount.end())
296 string strFile = (*mi).first;
297 int nRefCount = (*mi).second;
298 printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
301 // Move log data to the dat file
303 dbenv.txn_checkpoint(0, 0, 0);
304 printf("%s flush\n", strFile.c_str());
305 dbenv.lsn_reset(strFile.c_str(), 0);
306 mapFileUseCount.erase(mi++);
314 if (mapFileUseCount.empty())
316 dbenv.log_archive(&listp, DB_ARCH_REMOVE);
332 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
336 return Read(make_pair(string("tx"), hash), txindex);
339 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
342 return Write(make_pair(string("tx"), hash), txindex);
345 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
350 uint256 hash = tx.GetHash();
351 CTxIndex txindex(pos, tx.vout.size());
352 return Write(make_pair(string("tx"), hash), txindex);
355 bool CTxDB::EraseTxIndex(const CTransaction& tx)
358 uint256 hash = tx.GetHash();
360 return Erase(make_pair(string("tx"), hash));
363 bool CTxDB::ContainsTx(uint256 hash)
366 return Exists(make_pair(string("tx"), hash));
369 bool CTxDB::ReadOwnerTxes(uint160 hash160, int nMinHeight, vector<CTransaction>& vtx)
375 Dbc* pcursor = GetCursor();
379 unsigned int fFlags = DB_SET_RANGE;
384 if (fFlags == DB_SET_RANGE)
385 ssKey << string("owner") << hash160 << CDiskTxPos(0, 0, 0);
387 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
389 if (ret == DB_NOTFOUND)
401 ssKey >> strType >> hashItem >> pos;
403 ssValue >> nItemHeight;
406 if (strType != "owner" || hashItem != hash160)
408 if (nItemHeight >= nMinHeight)
410 vtx.resize(vtx.size()+1);
411 if (!vtx.back().ReadFromDisk(pos))
423 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
427 if (!ReadTxIndex(hash, txindex))
429 return (tx.ReadFromDisk(txindex.pos));
432 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
435 return ReadDiskTx(hash, tx, txindex);
438 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
440 return ReadDiskTx(outpoint.hash, tx, txindex);
443 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
446 return ReadDiskTx(outpoint.hash, tx, txindex);
449 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
451 return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
454 bool CTxDB::EraseBlockIndex(uint256 hash)
456 return Erase(make_pair(string("blockindex"), hash));
459 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
461 return Read(string("hashBestChain"), hashBestChain);
464 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
466 return Write(string("hashBestChain"), hashBestChain);
469 bool CTxDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
471 return Read(string("bnBestInvalidWork"), bnBestInvalidWork);
474 bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
476 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
479 CBlockIndex static * InsertBlockIndex(uint256 hash)
485 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
486 if (mi != mapBlockIndex.end())
490 CBlockIndex* pindexNew = new CBlockIndex();
492 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
493 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
494 pindexNew->phashBlock = &((*mi).first);
499 bool CTxDB::LoadBlockIndex()
501 // Get database cursor
502 Dbc* pcursor = GetCursor();
506 // Load mapBlockIndex
507 unsigned int fFlags = DB_SET_RANGE;
512 if (fFlags == DB_SET_RANGE)
513 ssKey << make_pair(string("blockindex"), uint256(0));
515 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
517 if (ret == DB_NOTFOUND)
525 if (strType == "blockindex")
527 CDiskBlockIndex diskindex;
528 ssValue >> diskindex;
530 // Construct block index object
531 CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
532 pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
533 pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
534 pindexNew->nFile = diskindex.nFile;
535 pindexNew->nBlockPos = diskindex.nBlockPos;
536 pindexNew->nHeight = diskindex.nHeight;
537 pindexNew->nVersion = diskindex.nVersion;
538 pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
539 pindexNew->nTime = diskindex.nTime;
540 pindexNew->nBits = diskindex.nBits;
541 pindexNew->nNonce = diskindex.nNonce;
543 // Watch for genesis block
544 if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
545 pindexGenesisBlock = pindexNew;
547 if (!pindexNew->CheckIndex())
548 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
557 // Calculate bnChainWork
558 vector<pair<int, CBlockIndex*> > vSortedByHeight;
559 vSortedByHeight.reserve(mapBlockIndex.size());
560 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
562 CBlockIndex* pindex = item.second;
563 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
565 sort(vSortedByHeight.begin(), vSortedByHeight.end());
566 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
568 CBlockIndex* pindex = item.second;
569 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
572 // Load hashBestChain pointer to end of best chain
573 if (!ReadHashBestChain(hashBestChain))
575 if (pindexGenesisBlock == NULL)
577 return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
579 if (!mapBlockIndex.count(hashBestChain))
580 return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
581 pindexBest = mapBlockIndex[hashBestChain];
582 nBestHeight = pindexBest->nHeight;
583 bnBestChainWork = pindexBest->bnChainWork;
584 printf("LoadBlockIndex(): hashBestChain=%s height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);
586 // Load bnBestInvalidWork, OK if it doesn't exist
587 ReadBestInvalidWork(bnBestInvalidWork);
589 // Verify blocks in the best chain
590 int nCheckLevel = GetArg("-checklevel", 1);
591 int nCheckDepth = GetArg( "-checkblocks", 2500);
592 if (nCheckDepth == 0)
593 nCheckDepth = 1000000000; // suffices until the year 19000
594 if (nCheckDepth > nBestHeight)
595 nCheckDepth = nBestHeight;
596 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
597 CBlockIndex* pindexFork = NULL;
598 map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
599 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
601 if (pindex->nHeight < nBestHeight-nCheckDepth)
604 if (!block.ReadFromDisk(pindex))
605 return error("LoadBlockIndex() : block.ReadFromDisk failed");
606 // check level 1: verify block validity
607 if (nCheckLevel>0 && !block.CheckBlock())
609 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
610 pindexFork = pindex->pprev;
612 // check level 2: verify transaction index validity
615 pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
616 mapBlockPos[pos] = pindex;
617 BOOST_FOREACH(const CTransaction &tx, block.vtx)
619 uint256 hashTx = tx.GetHash();
621 if (ReadTxIndex(hashTx, txindex))
623 // check level 3: checker transaction hashes
624 if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
626 // either an error or a duplicate transaction
627 CTransaction txFound;
628 if (!txFound.ReadFromDisk(txindex.pos))
630 printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
631 pindexFork = pindex->pprev;
634 if (txFound.GetHash() != hashTx) // not a duplicate tx
636 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
637 pindexFork = pindex->pprev;
640 // check level 4: check whether spent txouts were spent within the main chain
643 BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
647 pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
648 if (!mapBlockPos.count(posFind))
650 printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
651 pindexFork = pindex->pprev;
653 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
656 CTransaction txSpend;
657 if (!txSpend.ReadFromDisk(txpos))
659 printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
660 pindexFork = pindex->pprev;
662 else if (!txSpend.CheckTransaction())
664 printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
665 pindexFork = pindex->pprev;
670 BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
671 if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
675 printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
676 pindexFork = pindex->pprev;
684 // check level 5: check whether all prevouts are marked spent
686 BOOST_FOREACH(const CTxIn &txin, tx.vin)
689 if (ReadTxIndex(txin.prevout.hash, txindex))
690 if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
692 printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
693 pindexFork = pindex->pprev;
701 // Reorg back to the fork
702 printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
704 if (!block.ReadFromDisk(pindexFork))
705 return error("LoadBlockIndex() : block.ReadFromDisk failed");
707 block.SetBestChain(txdb, pindexFork);
721 bool CAddrDB::WriteAddrman(const CAddrMan& addrman)
723 return Write(string("addrman"), addrman);
726 bool CAddrDB::LoadAddresses()
728 if (Read(string("addrman"), addrman))
730 printf("Loaded %i addresses\n", addrman.size());
734 // Read pre-0.6 addr records
736 vector<CAddress> vAddr;
737 vector<vector<unsigned char> > vDelete;
740 Dbc* pcursor = GetCursor();
749 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
750 if (ret == DB_NOTFOUND)
758 if (strType == "addr")
762 vAddr.push_back(addr);
767 addrman.Add(vAddr, CNetAddr("0.0.0.0"));
768 printf("Loaded %i addresses\n", addrman.size());
770 // Note: old records left; we ran into hangs-on-startup
771 // bugs for some users who (we think) were running after
772 // an unclean shutdown.
779 return CAddrDB("cr+").LoadAddresses();
789 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
792 return Write(make_pair(string("name"), strAddress), strName);
795 bool CWalletDB::EraseName(const string& strAddress)
797 // This should only be used for sending addresses, never for receiving addresses,
798 // receiving addresses must always have an address book entry if they're not change return.
800 return Erase(make_pair(string("name"), strAddress));
803 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
806 return Read(make_pair(string("acc"), strAccount), account);
809 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
811 return Write(make_pair(string("acc"), strAccount), account);
814 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
816 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry);
819 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
821 list<CAccountingEntry> entries;
822 ListAccountCreditDebit(strAccount, entries);
824 int64 nCreditDebit = 0;
825 BOOST_FOREACH (const CAccountingEntry& entry, entries)
826 nCreditDebit += entry.nCreditDebit;
831 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
833 bool fAllAccounts = (strAccount == "*");
835 Dbc* pcursor = GetCursor();
837 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
838 unsigned int fFlags = DB_SET_RANGE;
843 if (fFlags == DB_SET_RANGE)
844 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
846 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
848 if (ret == DB_NOTFOUND)
853 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
859 if (strType != "acentry")
861 CAccountingEntry acentry;
862 ssKey >> acentry.strAccount;
863 if (!fAllAccounts && acentry.strAccount != strAccount)
867 entries.push_back(acentry);
874 int CWalletDB::LoadWallet(CWallet* pwallet)
876 pwallet->vchDefaultKey.clear();
877 int nFileVersion = 0;
878 vector<uint256> vWalletUpgrade;
879 bool fIsEncrypted = false;
881 //// todo: shouldn't we catch exceptions and try to recover and continue?
882 CRITICAL_BLOCK(pwallet->cs_wallet)
885 if (Read((string)"minversion", nMinVersion))
887 if (nMinVersion > CLIENT_VERSION)
889 pwallet->LoadMinVersion(nMinVersion);
893 Dbc* pcursor = GetCursor();
896 printf("Error getting wallet database cursor\n");
905 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
906 if (ret == DB_NOTFOUND)
910 printf("Error reading next record from wallet database\n");
915 // Taking advantage of the fact that pair serialization
916 // is just the two items serialized one after the other
919 if (strType == "name")
923 ssValue >> pwallet->mapAddressBook[strAddress];
925 else if (strType == "tx")
929 CWalletTx& wtx = pwallet->mapWallet[hash];
931 wtx.BindWallet(pwallet);
933 if (wtx.GetHash() != hash)
934 printf("Error in wallet.dat, hash mismatch\n");
936 // Undo serialize changes in 31600
937 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
939 if (!ssValue.empty())
943 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
944 printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
945 wtx.fTimeReceivedIsTxTime = fTmp;
949 printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
950 wtx.fTimeReceivedIsTxTime = 0;
952 vWalletUpgrade.push_back(hash);
956 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
957 //printf(" %12I64d %s %s %s\n",
958 // wtx.vout[0].nValue,
959 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
960 // wtx.hashBlock.ToString().substr(0,20).c_str(),
961 // wtx.mapValue["message"].c_str());
963 else if (strType == "acentry")
969 if (nNumber > nAccountingEntryNumber)
970 nAccountingEntryNumber = nNumber;
972 else if (strType == "key" || strType == "wkey")
974 vector<unsigned char> vchPubKey;
977 if (strType == "key")
981 key.SetPubKey(vchPubKey);
982 key.SetPrivKey(pkey);
983 if (key.GetPubKey() != vchPubKey)
985 printf("Error reading wallet database: CPrivKey pubkey inconsistency\n");
990 printf("Error reading wallet database: invalid CPrivKey\n");
998 key.SetPubKey(vchPubKey);
999 key.SetPrivKey(wkey.vchPrivKey);
1000 if (key.GetPubKey() != vchPubKey)
1002 printf("Error reading wallet database: CWalletKey pubkey inconsistency\n");
1007 printf("Error reading wallet database: invalid CWalletKey\n");
1011 if (!pwallet->LoadKey(key))
1013 printf("Error reading wallet database: LoadKey failed\n");
1017 else if (strType == "mkey")
1021 CMasterKey kMasterKey;
1022 ssValue >> kMasterKey;
1023 if(pwallet->mapMasterKeys.count(nID) != 0)
1025 printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID);
1028 pwallet->mapMasterKeys[nID] = kMasterKey;
1029 if (pwallet->nMasterKeyMaxID < nID)
1030 pwallet->nMasterKeyMaxID = nID;
1032 else if (strType == "ckey")
1034 vector<unsigned char> vchPubKey;
1036 vector<unsigned char> vchPrivKey;
1037 ssValue >> vchPrivKey;
1038 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
1040 printf("Error reading wallet database: LoadCryptedKey failed\n");
1043 fIsEncrypted = true;
1045 else if (strType == "defaultkey")
1047 ssValue >> pwallet->vchDefaultKey;
1049 else if (strType == "pool")
1053 pwallet->setKeyPool.insert(nIndex);
1055 else if (strType == "version")
1057 ssValue >> nFileVersion;
1058 if (nFileVersion == 10300)
1061 else if (strType == "cscript")
1067 if (!pwallet->LoadCScript(script))
1069 printf("Error reading wallet database: LoadCScript failed\n");
1077 BOOST_FOREACH(uint256 hash, vWalletUpgrade)
1078 WriteTx(hash, pwallet->mapWallet[hash]);
1080 printf("nFileVersion = %d\n", nFileVersion);
1083 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
1084 if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
1085 return DB_NEED_REWRITE;
1087 if (nFileVersion < CLIENT_VERSION) // Update
1089 // Get rid of old debug.log file in current directory
1090 if (nFileVersion <= 105 && !pszSetDataDir[0])
1091 unlink("debug.log");
1093 WriteVersion(CLIENT_VERSION);
1099 void ThreadFlushWalletDB(void* parg)
1101 const string& strFile = ((const string*)parg)[0];
1102 static bool fOneThread;
1106 if (!GetBoolArg("-flushwallet", true))
1109 unsigned int nLastSeen = nWalletDBUpdated;
1110 unsigned int nLastFlushed = nWalletDBUpdated;
1111 int64 nLastWalletUpdate = GetTime();
1116 if (nLastSeen != nWalletDBUpdated)
1118 nLastSeen = nWalletDBUpdated;
1119 nLastWalletUpdate = GetTime();
1122 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
1124 TRY_CRITICAL_BLOCK(cs_db)
1126 // Don't do this if any databases are in use
1128 map<string, int>::iterator mi = mapFileUseCount.begin();
1129 while (mi != mapFileUseCount.end())
1131 nRefCount += (*mi).second;
1135 if (nRefCount == 0 && !fShutdown)
1137 map<string, int>::iterator mi = mapFileUseCount.find(strFile);
1138 if (mi != mapFileUseCount.end())
1140 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1141 printf("Flushing wallet.dat\n");
1142 nLastFlushed = nWalletDBUpdated;
1143 int64 nStart = GetTimeMillis();
1145 // Flush wallet.dat so it's self contained
1147 dbenv.txn_checkpoint(0, 0, 0);
1148 dbenv.lsn_reset(strFile.c_str(), 0);
1150 mapFileUseCount.erase(mi++);
1151 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
1159 bool BackupWallet(const CWallet& wallet, const string& strDest)
1161 if (!wallet.fFileBacked)
1165 CRITICAL_BLOCK(cs_db)
1167 if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
1169 // Flush log data to the dat file
1170 CloseDb(wallet.strWalletFile);
1171 dbenv.txn_checkpoint(0, 0, 0);
1172 dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
1173 mapFileUseCount.erase(wallet.strWalletFile);
1176 filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
1177 pathSrc.make_preferred();
1178 filesystem::path pathDest(strDest);
1179 pathDest.make_preferred();
1180 if (filesystem::is_directory(pathDest))
1181 pathDest = pathDest / wallet.strWalletFile;
1184 #if BOOST_VERSION >= 104000
1185 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
1187 filesystem::copy_file(pathSrc, pathDest);
1189 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
1191 } catch(const filesystem::filesystem_error &e) {
1192 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());