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 COPYING or http://www.opensource.org/licenses/mit-license.php.
13 #include <boost/version.hpp>
14 #include <boost/filesystem.hpp>
15 #include <boost/algorithm/string.hpp>
17 #include <boost/date_time/posix_time/posix_time.hpp>
18 #include <boost/lexical_cast.hpp>
19 #include <boost/variant/get.hpp>
20 #include <boost/algorithm/string.hpp>
23 using namespace boost;
26 static uint64_t nAccountingEntryNumber = 0;
27 extern bool fWalletUnlockMintOnly;
33 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
36 return Write(make_pair(string("name"), strAddress), strName);
39 bool CWalletDB::EraseName(const string& strAddress)
41 // This should only be used for sending addresses, never for receiving addresses,
42 // receiving addresses must always have an address book entry if they're not change return.
44 return Erase(make_pair(string("name"), strAddress));
47 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
50 return Read(make_pair(string("acc"), strAccount), account);
53 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
55 return Write(make_pair(string("acc"), strAccount), account);
58 bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
60 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
63 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
65 return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
68 int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount)
70 list<CAccountingEntry> entries;
71 ListAccountCreditDebit(strAccount, entries);
73 int64_t nCreditDebit = 0;
74 BOOST_FOREACH (const CAccountingEntry& entry, entries)
75 nCreditDebit += entry.nCreditDebit;
80 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
82 bool fAllAccounts = (strAccount == "*");
84 Dbc* pcursor = GetCursor();
86 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
87 unsigned int fFlags = DB_SET_RANGE;
91 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
92 if (fFlags == DB_SET_RANGE)
93 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0));
94 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
95 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
97 if (ret == DB_NOTFOUND)
102 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
108 if (strType != "acentry")
110 CAccountingEntry acentry;
111 ssKey >> acentry.strAccount;
112 if (!fAllAccounts && acentry.strAccount != strAccount)
116 ssKey >> acentry.nEntryNo;
117 entries.push_back(acentry);
125 CWalletDB::ReorderTransactions(CWallet* pwallet)
127 LOCK(pwallet->cs_wallet);
128 // Old wallets didn't have any defined order for transactions
129 // Probably a bad idea to change the output of this
131 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
132 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
133 typedef multimap<int64_t, TxPair > TxItems;
136 for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
138 CWalletTx* wtx = &((*it).second);
139 txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
141 list<CAccountingEntry> acentries;
142 ListAccountCreditDebit("", acentries);
143 BOOST_FOREACH(CAccountingEntry& entry, acentries)
145 txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
148 int64_t& nOrderPosNext = pwallet->nOrderPosNext;
150 std::vector<int64_t> nOrderPosOffsets;
151 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
153 CWalletTx *const pwtx = (*it).second.first;
154 CAccountingEntry *const pacentry = (*it).second.second;
155 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
159 nOrderPos = nOrderPosNext++;
160 nOrderPosOffsets.push_back(nOrderPos);
163 // Have to write accounting regardless, since we don't keep it in memory
164 if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
169 int64_t nOrderPosOff = 0;
170 BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
172 if (nOrderPos >= nOffsetStart)
175 nOrderPos += nOrderPosOff;
176 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
181 // Since we're changing the order, write it back
184 if (!WriteTx(pwtx->GetHash(), *pwtx))
188 if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
196 class CWalletScanState {
200 unsigned int nKeyMeta;
204 vector<uint256> vWalletUpgrade;
207 nKeys = nCKeys = nKeyMeta = 0;
208 fIsEncrypted = false;
209 fAnyUnordered = false;
215 ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
216 CWalletScanState &wss, string& strType, string& strErr)
220 // Taking advantage of the fact that pair serialization
221 // is just the two items serialized one after the other
224 if (strType == "name")
228 ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()];
230 else if (strType == "tx")
234 CWalletTx& wtx = pwallet->mapWallet[hash];
236 if (wtx.CheckTransaction() && (wtx.GetHash() == hash))
237 wtx.BindWallet(pwallet);
240 pwallet->mapWallet.erase(hash);
244 // Undo serialize changes in 31600
245 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
247 if (!ssValue.empty())
251 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
252 strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
253 wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
254 wtx.fTimeReceivedIsTxTime = fTmp;
258 strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
259 wtx.fTimeReceivedIsTxTime = 0;
261 wss.vWalletUpgrade.push_back(hash);
264 if (wtx.nOrderPos == -1)
265 wss.fAnyUnordered = true;
268 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
269 //printf(" %12"PRId64" %s %s %s\n",
270 // wtx.vout[0].nValue,
271 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
272 // wtx.hashBlock.ToString().substr(0,20).c_str(),
273 // wtx.mapValue["message"].c_str());
275 else if (strType == "acentry")
281 if (nNumber > nAccountingEntryNumber)
282 nAccountingEntryNumber = nNumber;
284 if (!wss.fAnyUnordered)
286 CAccountingEntry acentry;
288 if (acentry.nOrderPos == -1)
289 wss.fAnyUnordered = true;
292 else if (strType == "watchs")
299 pwallet->LoadWatchOnly(script);
301 // Watch-only addresses have no birthday information for now,
302 // so set the wallet birthday to the beginning of time.
303 pwallet->nTimeFirstKey = 1;
305 else if (strType == "malpair")
311 ssValue >> vchSecret;
313 CMalleableKeyView keyView(strKeyView);
314 if (!pwallet->LoadMalleableKey(keyView, vchSecret))
316 strErr = "Error reading wallet database: LoadMalleableKey failed";
320 else if (strType == "malcpair")
324 std::vector<unsigned char> vchCryptedSecret;
326 ssValue >> vchCryptedSecret;
328 CMalleableKeyView keyView(strKeyView);
329 if (!pwallet->LoadCryptedMalleableKey(keyView, vchCryptedSecret))
331 strErr = "Error reading wallet database: LoadCryptedMalleableKey failed";
335 else if (strType == "key" || strType == "wkey")
337 vector<unsigned char> vchPubKey;
340 if (strType == "key")
345 key.SetPubKey(vchPubKey);
346 if (!key.SetPrivKey(pkey))
348 strErr = "Error reading wallet database: CPrivKey corrupt";
351 if (key.GetPubKey() != vchPubKey)
353 strErr = "Error reading wallet database: CPrivKey pubkey inconsistency";
358 strErr = "Error reading wallet database: invalid CPrivKey";
366 key.SetPubKey(vchPubKey);
367 if (!key.SetPrivKey(wkey.vchPrivKey))
369 strErr = "Error reading wallet database: CPrivKey corrupt";
372 if (key.GetPubKey() != vchPubKey)
374 strErr = "Error reading wallet database: CWalletKey pubkey inconsistency";
379 strErr = "Error reading wallet database: invalid CWalletKey";
383 if (!pwallet->LoadKey(key))
385 strErr = "Error reading wallet database: LoadKey failed";
389 else if (strType == "mkey")
393 CMasterKey kMasterKey;
394 ssValue >> kMasterKey;
396 if(pwallet->mapMasterKeys.count(nID) != 0)
398 strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
401 pwallet->mapMasterKeys[nID] = kMasterKey;
402 if (pwallet->nMasterKeyMaxID < nID)
403 pwallet->nMasterKeyMaxID = nID;
405 else if (strType == "ckey")
408 vector<unsigned char> vchPubKey;
410 vector<unsigned char> vchPrivKey;
411 ssValue >> vchPrivKey;
412 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
414 strErr = "Error reading wallet database: LoadCryptedKey failed";
417 wss.fIsEncrypted = true;
419 else if (strType == "malmeta")
424 CMalleableKeyView keyView;
425 keyView.SetString(strKeyView);
427 CKeyMetadata keyMeta;
431 pwallet->LoadMalleableKeyMetadata(keyView, keyMeta);
433 else if (strType == "keymeta")
437 CKeyMetadata keyMeta;
441 pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
443 // find earliest key creation time, as wallet birthday
444 if (!pwallet->nTimeFirstKey ||
445 (keyMeta.nCreateTime < pwallet->nTimeFirstKey))
446 pwallet->nTimeFirstKey = keyMeta.nCreateTime;
448 else if (strType == "defaultkey")
450 ssValue >> pwallet->vchDefaultKey;
452 else if (strType == "pool")
458 pwallet->setKeyPool.insert(nIndex);
460 // If no metadata exists yet, create a default with the pool key's
461 // creation time. Note that this may be overwritten by actually
462 // stored metadata for that key later, which is fine.
463 CKeyID keyid = keypool.vchPubKey.GetID();
464 if (pwallet->mapKeyMetadata.count(keyid) == 0)
465 pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
468 else if (strType == "version")
470 ssValue >> wss.nFileVersion;
471 if (wss.nFileVersion == 10300)
472 wss.nFileVersion = 300;
474 else if (strType == "cscript")
480 if (!pwallet->LoadCScript(script))
482 strErr = "Error reading wallet database: LoadCScript failed";
486 else if (strType == "orderposnext")
488 ssValue >> pwallet->nOrderPosNext;
497 static bool IsKeyType(string strType)
499 return (strType== "key" || strType == "wkey" ||
500 strType == "mkey" || strType == "ckey" || strType == "malpair" || strType == "malcpair");
503 DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
505 pwallet->vchDefaultKey = CPubKey();
506 CWalletScanState wss;
507 bool fNoncriticalErrors = false;
508 DBErrors result = DB_LOAD_OK;
511 LOCK(pwallet->cs_wallet);
513 if (Read((string)"minversion", nMinVersion))
515 if (nMinVersion > CLIENT_VERSION)
517 pwallet->LoadMinVersion(nMinVersion);
521 Dbc* pcursor = GetCursor();
524 printf("Error getting wallet database cursor\n");
531 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
532 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
533 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
534 if (ret == DB_NOTFOUND)
538 printf("Error reading next record from wallet database\n");
542 // Try to be tolerant of single corrupt records:
543 string strType, strErr;
544 if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
546 // losing keys is considered a catastrophic error, anything else
547 // we assume the user can live with:
548 if (IsKeyType(strType))
552 // Leave other errors alone, if we try to fix them we might make things worse.
553 fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
555 // Rescan if there is a bad transaction record:
556 SoftSetBoolArg("-rescan", true);
560 printf("%s\n", strErr.c_str());
569 if (fNoncriticalErrors && result == DB_LOAD_OK)
570 result = DB_NONCRITICAL_ERROR;
572 // Any wallet corruption at all: skip any rewriting or
573 // upgrading, we don't want to make it worse.
574 if (result != DB_LOAD_OK)
577 printf("nFileVersion = %d\n", wss.nFileVersion);
579 printf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
580 wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
582 // nTimeFirstKey is only reliable if all keys have metadata
583 if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
584 pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
587 BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
588 WriteTx(hash, pwallet->mapWallet[hash]);
590 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
591 if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
592 return DB_NEED_REWRITE;
594 if (wss.nFileVersion < CLIENT_VERSION) // Update
595 WriteVersion(CLIENT_VERSION);
597 if (wss.fAnyUnordered)
598 result = ReorderTransactions(pwallet);
603 DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash)
605 pwallet->vchDefaultKey = CPubKey();
606 CWalletScanState wss;
607 bool fNoncriticalErrors = false;
608 DBErrors result = DB_LOAD_OK;
611 LOCK(pwallet->cs_wallet);
613 if (Read((string)"minversion", nMinVersion))
615 if (nMinVersion > CLIENT_VERSION)
617 pwallet->LoadMinVersion(nMinVersion);
621 Dbc* pcursor = GetCursor();
624 printf("Error getting wallet database cursor\n");
631 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
632 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
633 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
634 if (ret == DB_NOTFOUND)
638 printf("Error reading next record from wallet database\n");
644 if (strType == "tx") {
648 vTxHash.push_back(hash);
653 catch (boost::thread_interrupted) {
660 if (fNoncriticalErrors && result == DB_LOAD_OK)
661 result = DB_NONCRITICAL_ERROR;
666 DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet)
668 // build list of wallet TXs
669 vector<uint256> vTxHash;
670 DBErrors err = FindWalletTx(pwallet, vTxHash);
671 if (err != DB_LOAD_OK)
674 // erase each wallet TX
675 BOOST_FOREACH (uint256& hash, vTxHash) {
683 void ThreadFlushWalletDB(void* parg)
685 // Make this thread recognisable as the wallet flushing thread
686 RenameThread("novacoin-wallet");
688 const string& strFile = ((const string*)parg)[0];
689 static bool fOneThread;
693 if (!GetBoolArg("-flushwallet", true))
696 unsigned int nLastSeen = nWalletDBUpdated;
697 unsigned int nLastFlushed = nWalletDBUpdated;
698 int64_t nLastWalletUpdate = GetTime();
703 if (nLastSeen != nWalletDBUpdated)
705 nLastSeen = nWalletDBUpdated;
706 nLastWalletUpdate = GetTime();
709 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
711 TRY_LOCK(bitdb.cs_db,lockDb);
714 // Don't do this if any databases are in use
716 map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
717 while (mi != bitdb.mapFileUseCount.end())
719 nRefCount += (*mi).second;
723 if (nRefCount == 0 && !fShutdown)
725 map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
726 if (mi != bitdb.mapFileUseCount.end())
728 printf("Flushing wallet.dat\n");
729 nLastFlushed = nWalletDBUpdated;
730 int64_t nStart = GetTimeMillis();
732 // Flush wallet.dat so it's self contained
733 bitdb.CloseDb(strFile);
734 bitdb.CheckpointLSN(strFile);
736 bitdb.mapFileUseCount.erase(mi++);
737 printf("Flushed wallet.dat %" PRId64 "ms\n", GetTimeMillis() - nStart);
745 bool BackupWallet(const CWallet& wallet, const string& strDest)
747 if (!wallet.fFileBacked)
753 if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
755 // Flush log data to the dat file
756 bitdb.CloseDb(wallet.strWalletFile);
757 bitdb.CheckpointLSN(wallet.strWalletFile);
758 bitdb.mapFileUseCount.erase(wallet.strWalletFile);
761 filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
762 filesystem::path pathDest(strDest);
763 if (filesystem::is_directory(pathDest))
764 pathDest /= wallet.strWalletFile;
767 #if BOOST_VERSION >= 104000
768 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
770 filesystem::copy_file(pathSrc, pathDest);
772 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
774 } catch(const filesystem::filesystem_error &e) {
775 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
785 bool DumpWallet(CWallet* pwallet, const string& strDest)
788 if (!pwallet->fFileBacked)
793 std::map<CKeyID, int64_t> mapKeyBirth;
794 std::set<CKeyID> setKeyPool;
795 pwallet->GetKeyBirthTimes(mapKeyBirth);
796 pwallet->GetAllReserveKeys(setKeyPool);
798 // sort time/key pairs
799 std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
800 for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
801 vKeyBirth.push_back(std::make_pair(it->second, it->first));
804 std::sort(vKeyBirth.begin(), vKeyBirth.end());
806 // open outputfile as a stream
808 file.open(strDest.c_str());
813 file << strprintf("# Wallet dump created by NovaCoin %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str());
814 file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str());
815 file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString().c_str());
816 file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime).c_str());
818 for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
819 const CKeyID &keyid = it->second;
820 std::string strTime = EncodeDumpTime(it->first);
821 std::string strAddr = CBitcoinAddress(keyid).ToString();
825 if (pwallet->GetKey(keyid, key)) {
826 if (pwallet->mapAddressBook.count(keyid)) {
827 CSecret secret = key.GetSecret(IsCompressed);
828 file << strprintf("%s %s label=%s # addr=%s\n",
829 CBitcoinSecret(secret, IsCompressed).ToString().c_str(),
831 EncodeDumpString(pwallet->mapAddressBook[keyid]).c_str(),
833 } else if (setKeyPool.count(keyid)) {
834 CSecret secret = key.GetSecret(IsCompressed);
835 file << strprintf("%s %s reserve=1 # addr=%s\n",
836 CBitcoinSecret(secret, IsCompressed).ToString().c_str(),
840 CSecret secret = key.GetSecret(IsCompressed);
841 file << strprintf("%s %s change=1 # addr=%s\n",
842 CBitcoinSecret(secret, IsCompressed).ToString().c_str(),
849 file << "# End of dump\n";
857 bool ImportWallet(CWallet *pwallet, const string& strLocation)
860 if (!pwallet->fFileBacked)
864 // open inputfile as stream
866 file.open(strLocation.c_str());
870 int64_t nTimeBegin = pindexBest->nTime;
874 // read through input file checking and importing keys into wallet.
875 while (file.good()) {
877 std::getline(file, line);
878 if (line.empty() || line[0] == '#')
881 std::vector<std::string> vstr;
882 boost::split(vstr, line, boost::is_any_of(" "));
885 CBitcoinSecret vchSecret;
886 if (!vchSecret.SetString(vstr[0]))
891 CSecret secret = vchSecret.GetSecret(fCompressed);
892 key.SetSecret(secret, fCompressed);
893 CKeyID keyid = key.GetPubKey().GetID();
895 if (pwallet->HaveKey(keyid)) {
896 printf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str());
899 int64_t nTime = DecodeDumpTime(vstr[1]);
900 std::string strLabel;
902 for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
903 if (boost::algorithm::starts_with(vstr[nStr], "#"))
905 if (vstr[nStr] == "change=1")
907 if (vstr[nStr] == "reserve=1")
909 if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
910 strLabel = DecodeDumpString(vstr[nStr].substr(6));
914 printf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str());
915 if (!pwallet->AddKey(key)) {
919 pwallet->mapKeyMetadata[keyid].nCreateTime = nTime;
921 pwallet->SetAddressBookName(keyid, strLabel);
922 nTimeBegin = std::min(nTimeBegin, nTime);
926 // rescan block chain looking for coins from new keys
927 CBlockIndex *pindex = pindexBest;
928 while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200)
929 pindex = pindex->pprev;
931 printf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1);
932 pwallet->ScanForWalletTransactions(pindex);
933 pwallet->ReacceptWalletTransactions();
934 pwallet->MarkDirty();
946 // Try to (very carefully!) recover wallet.dat if there is a problem.
948 bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
950 // Recovery procedure:
951 // move wallet.dat to wallet.timestamp.bak
952 // Call Salvage with fAggressive=true to
953 // get as much data as possible.
954 // Rewrite salvaged data to wallet.dat
955 // Set -rescan so any missing transactions will be
957 int64_t now = GetTime();
958 std::string newFilename = strprintf("wallet.%" PRId64 ".bak", now);
960 int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
961 newFilename.c_str(), DB_AUTO_COMMIT);
963 printf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str());
966 printf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str());
970 std::vector<CDBEnv::KeyValPair> salvagedData;
971 bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
972 if (salvagedData.empty())
974 printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
977 printf("Salvage(aggressive) found %" PRIszu " records\n", salvagedData.size());
979 bool fSuccess = allOK;
980 Db* pdbCopy = new Db(&dbenv.dbenv, 0);
981 int ret = pdbCopy->open(NULL, // Txn pointer
982 filename.c_str(), // Filename
983 "main", // Logical db name
984 DB_BTREE, // Database type
989 printf("Cannot create database file %s\n", filename.c_str());
993 CWalletScanState wss;
995 DbTxn* ptxn = dbenv.TxnBegin();
996 BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
1000 CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
1001 CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
1002 string strType, strErr;
1003 bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
1004 wss, strType, strErr);
1005 if (!IsKeyType(strType))
1009 printf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str());
1013 Dbt datKey(&row.first[0], row.first.size());
1014 Dbt datValue(&row.second[0], row.second.size());
1015 int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
1026 bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
1028 return CWalletDB::Recover(dbenv, filename, false);