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
223 if (strType == "name")
227 ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()];
229 else if (strType == "tx")
233 CWalletTx& wtx = pwallet->mapWallet[hash];
235 if (wtx.CheckTransaction() && (wtx.GetHash() == hash))
236 wtx.BindWallet(pwallet);
239 pwallet->mapWallet.erase(hash);
243 // Undo serialize changes in 31600
244 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
246 if (!ssValue.empty())
250 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
251 strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
252 wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
253 wtx.fTimeReceivedIsTxTime = fTmp;
257 strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
258 wtx.fTimeReceivedIsTxTime = 0;
260 wss.vWalletUpgrade.push_back(hash);
263 if (wtx.nOrderPos == -1)
264 wss.fAnyUnordered = true;
267 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
268 //printf(" %12"PRId64" %s %s %s\n",
269 // wtx.vout[0].nValue,
270 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
271 // wtx.hashBlock.ToString().substr(0,20).c_str(),
272 // wtx.mapValue["message"].c_str());
274 else if (strType == "acentry")
280 if (nNumber > nAccountingEntryNumber)
281 nAccountingEntryNumber = nNumber;
283 if (!wss.fAnyUnordered)
285 CAccountingEntry acentry;
287 if (acentry.nOrderPos == -1)
288 wss.fAnyUnordered = true;
291 else if (strType == "watchs")
298 pwallet->LoadWatchOnly(script);
300 // Watch-only addresses have no birthday information for now,
301 // so set the wallet birthday to the beginning of time.
302 pwallet->nTimeFirstKey = 1;
304 else if (strType == "key" || strType == "wkey")
306 vector<unsigned char> vchPubKey;
309 if (strType == "key")
314 key.SetPubKey(vchPubKey);
315 if (!key.SetPrivKey(pkey))
317 strErr = "Error reading wallet database: CPrivKey corrupt";
320 if (key.GetPubKey() != vchPubKey)
322 strErr = "Error reading wallet database: CPrivKey pubkey inconsistency";
327 strErr = "Error reading wallet database: invalid CPrivKey";
335 key.SetPubKey(vchPubKey);
336 if (!key.SetPrivKey(wkey.vchPrivKey))
338 strErr = "Error reading wallet database: CPrivKey corrupt";
341 if (key.GetPubKey() != vchPubKey)
343 strErr = "Error reading wallet database: CWalletKey pubkey inconsistency";
348 strErr = "Error reading wallet database: invalid CWalletKey";
352 if (!pwallet->LoadKey(key))
354 strErr = "Error reading wallet database: LoadKey failed";
358 else if (strType == "mkey")
362 CMasterKey kMasterKey;
363 ssValue >> kMasterKey;
365 if(pwallet->mapMasterKeys.count(nID) != 0)
367 strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
370 pwallet->mapMasterKeys[nID] = kMasterKey;
371 if (pwallet->nMasterKeyMaxID < nID)
372 pwallet->nMasterKeyMaxID = nID;
374 else if (strType == "ckey")
377 vector<unsigned char> vchPubKey;
379 vector<unsigned char> vchPrivKey;
380 ssValue >> vchPrivKey;
381 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
383 strErr = "Error reading wallet database: LoadCryptedKey failed";
386 wss.fIsEncrypted = true;
388 else if (strType == "keymeta")
392 CKeyMetadata keyMeta;
396 pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
398 // find earliest key creation time, as wallet birthday
399 if (!pwallet->nTimeFirstKey ||
400 (keyMeta.nCreateTime < pwallet->nTimeFirstKey))
401 pwallet->nTimeFirstKey = keyMeta.nCreateTime;
403 else if (strType == "defaultkey")
405 ssValue >> pwallet->vchDefaultKey;
407 else if (strType == "pool")
413 pwallet->setKeyPool.insert(nIndex);
415 // If no metadata exists yet, create a default with the pool key's
416 // creation time. Note that this may be overwritten by actually
417 // stored metadata for that key later, which is fine.
418 CKeyID keyid = keypool.vchPubKey.GetID();
419 if (pwallet->mapKeyMetadata.count(keyid) == 0)
420 pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
423 else if (strType == "version")
425 ssValue >> wss.nFileVersion;
426 if (wss.nFileVersion == 10300)
427 wss.nFileVersion = 300;
429 else if (strType == "cscript")
435 if (!pwallet->LoadCScript(script))
437 strErr = "Error reading wallet database: LoadCScript failed";
441 else if (strType == "orderposnext")
443 ssValue >> pwallet->nOrderPosNext;
452 static bool IsKeyType(string strType)
454 return (strType== "key" || strType == "wkey" ||
455 strType == "mkey" || strType == "ckey");
458 DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
460 pwallet->vchDefaultKey = CPubKey();
461 CWalletScanState wss;
462 bool fNoncriticalErrors = false;
463 DBErrors result = DB_LOAD_OK;
466 LOCK(pwallet->cs_wallet);
468 if (Read((string)"minversion", nMinVersion))
470 if (nMinVersion > CLIENT_VERSION)
472 pwallet->LoadMinVersion(nMinVersion);
476 Dbc* pcursor = GetCursor();
479 printf("Error getting wallet database cursor\n");
486 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
487 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
488 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
489 if (ret == DB_NOTFOUND)
493 printf("Error reading next record from wallet database\n");
497 // Try to be tolerant of single corrupt records:
498 string strType, strErr;
499 if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
501 // losing keys is considered a catastrophic error, anything else
502 // we assume the user can live with:
503 if (IsKeyType(strType))
507 // Leave other errors alone, if we try to fix them we might make things worse.
508 fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
510 // Rescan if there is a bad transaction record:
511 SoftSetBoolArg("-rescan", true);
515 printf("%s\n", strErr.c_str());
524 if (fNoncriticalErrors && result == DB_LOAD_OK)
525 result = DB_NONCRITICAL_ERROR;
527 // Any wallet corruption at all: skip any rewriting or
528 // upgrading, we don't want to make it worse.
529 if (result != DB_LOAD_OK)
532 printf("nFileVersion = %d\n", wss.nFileVersion);
534 printf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
535 wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
537 // nTimeFirstKey is only reliable if all keys have metadata
538 if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
539 pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
542 BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
543 WriteTx(hash, pwallet->mapWallet[hash]);
545 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
546 if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
547 return DB_NEED_REWRITE;
549 if (wss.nFileVersion < CLIENT_VERSION) // Update
550 WriteVersion(CLIENT_VERSION);
552 if (wss.fAnyUnordered)
553 result = ReorderTransactions(pwallet);
558 DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash)
560 pwallet->vchDefaultKey = CPubKey();
561 CWalletScanState wss;
562 bool fNoncriticalErrors = false;
563 DBErrors result = DB_LOAD_OK;
566 LOCK(pwallet->cs_wallet);
568 if (Read((string)"minversion", nMinVersion))
570 if (nMinVersion > CLIENT_VERSION)
572 pwallet->LoadMinVersion(nMinVersion);
576 Dbc* pcursor = GetCursor();
579 printf("Error getting wallet database cursor\n");
586 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
587 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
588 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
589 if (ret == DB_NOTFOUND)
593 printf("Error reading next record from wallet database\n");
599 if (strType == "tx") {
603 vTxHash.push_back(hash);
608 catch (boost::thread_interrupted) {
615 if (fNoncriticalErrors && result == DB_LOAD_OK)
616 result = DB_NONCRITICAL_ERROR;
621 DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet)
623 // build list of wallet TXs
624 vector<uint256> vTxHash;
625 DBErrors err = FindWalletTx(pwallet, vTxHash);
626 if (err != DB_LOAD_OK)
629 // erase each wallet TX
630 BOOST_FOREACH (uint256& hash, vTxHash) {
638 void ThreadFlushWalletDB(void* parg)
640 // Make this thread recognisable as the wallet flushing thread
641 RenameThread("novacoin-wallet");
643 const string& strFile = ((const string*)parg)[0];
644 static bool fOneThread;
648 if (!GetBoolArg("-flushwallet", true))
651 unsigned int nLastSeen = nWalletDBUpdated;
652 unsigned int nLastFlushed = nWalletDBUpdated;
653 int64_t nLastWalletUpdate = GetTime();
658 if (nLastSeen != nWalletDBUpdated)
660 nLastSeen = nWalletDBUpdated;
661 nLastWalletUpdate = GetTime();
664 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
666 TRY_LOCK(bitdb.cs_db,lockDb);
669 // Don't do this if any databases are in use
671 map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
672 while (mi != bitdb.mapFileUseCount.end())
674 nRefCount += (*mi).second;
678 if (nRefCount == 0 && !fShutdown)
680 map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
681 if (mi != bitdb.mapFileUseCount.end())
683 printf("Flushing wallet.dat\n");
684 nLastFlushed = nWalletDBUpdated;
685 int64_t nStart = GetTimeMillis();
687 // Flush wallet.dat so it's self contained
688 bitdb.CloseDb(strFile);
689 bitdb.CheckpointLSN(strFile);
691 bitdb.mapFileUseCount.erase(mi++);
692 printf("Flushed wallet.dat %" PRId64 "ms\n", GetTimeMillis() - nStart);
700 bool BackupWallet(const CWallet& wallet, const string& strDest)
702 if (!wallet.fFileBacked)
708 if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
710 // Flush log data to the dat file
711 bitdb.CloseDb(wallet.strWalletFile);
712 bitdb.CheckpointLSN(wallet.strWalletFile);
713 bitdb.mapFileUseCount.erase(wallet.strWalletFile);
716 filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
717 filesystem::path pathDest(strDest);
718 if (filesystem::is_directory(pathDest))
719 pathDest /= wallet.strWalletFile;
722 #if BOOST_VERSION >= 104000
723 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
725 filesystem::copy_file(pathSrc, pathDest);
727 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
729 } catch(const filesystem::filesystem_error &e) {
730 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
740 bool DumpWallet(CWallet* pwallet, const string& strDest)
743 if (!pwallet->fFileBacked)
748 std::map<CKeyID, int64_t> mapKeyBirth;
749 std::set<CKeyID> setKeyPool;
750 pwallet->GetKeyBirthTimes(mapKeyBirth);
751 pwallet->GetAllReserveKeys(setKeyPool);
753 // sort time/key pairs
754 std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
755 for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
756 vKeyBirth.push_back(std::make_pair(it->second, it->first));
759 std::sort(vKeyBirth.begin(), vKeyBirth.end());
761 // open outputfile as a stream
763 file.open(strDest.c_str());
768 file << strprintf("# Wallet dump created by NovaCoin %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str());
769 file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str());
770 file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString().c_str());
771 file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime).c_str());
773 for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
774 const CKeyID &keyid = it->second;
775 std::string strTime = EncodeDumpTime(it->first);
776 std::string strAddr = CBitcoinAddress(keyid).ToString();
780 if (pwallet->GetKey(keyid, key)) {
781 if (pwallet->mapAddressBook.count(keyid)) {
782 CSecret secret = key.GetSecret(IsCompressed);
783 file << strprintf("%s %s label=%s # addr=%s\n",
784 CBitcoinSecret(secret, IsCompressed).ToString().c_str(),
786 EncodeDumpString(pwallet->mapAddressBook[keyid]).c_str(),
788 } else if (setKeyPool.count(keyid)) {
789 CSecret secret = key.GetSecret(IsCompressed);
790 file << strprintf("%s %s reserve=1 # addr=%s\n",
791 CBitcoinSecret(secret, IsCompressed).ToString().c_str(),
795 CSecret secret = key.GetSecret(IsCompressed);
796 file << strprintf("%s %s change=1 # addr=%s\n",
797 CBitcoinSecret(secret, IsCompressed).ToString().c_str(),
804 file << "# End of dump\n";
812 bool ImportWallet(CWallet *pwallet, const string& strLocation)
815 if (!pwallet->fFileBacked)
819 // open inputfile as stream
821 file.open(strLocation.c_str());
825 int64_t nTimeBegin = pindexBest->nTime;
829 // read through input file checking and importing keys into wallet.
830 while (file.good()) {
832 std::getline(file, line);
833 if (line.empty() || line[0] == '#')
836 std::vector<std::string> vstr;
837 boost::split(vstr, line, boost::is_any_of(" "));
840 CBitcoinSecret vchSecret;
841 if (!vchSecret.SetString(vstr[0]))
846 CSecret secret = vchSecret.GetSecret(fCompressed);
847 key.SetSecret(secret, fCompressed);
848 CKeyID keyid = key.GetPubKey().GetID();
850 if (pwallet->HaveKey(keyid)) {
851 printf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str());
854 int64_t nTime = DecodeDumpTime(vstr[1]);
855 std::string strLabel;
857 for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
858 if (boost::algorithm::starts_with(vstr[nStr], "#"))
860 if (vstr[nStr] == "change=1")
862 if (vstr[nStr] == "reserve=1")
864 if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
865 strLabel = DecodeDumpString(vstr[nStr].substr(6));
869 printf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str());
870 if (!pwallet->AddKey(key)) {
874 pwallet->mapKeyMetadata[keyid].nCreateTime = nTime;
876 pwallet->SetAddressBookName(keyid, strLabel);
877 nTimeBegin = std::min(nTimeBegin, nTime);
881 // rescan block chain looking for coins from new keys
882 CBlockIndex *pindex = pindexBest;
883 while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200)
884 pindex = pindex->pprev;
886 printf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1);
887 pwallet->ScanForWalletTransactions(pindex);
888 pwallet->ReacceptWalletTransactions();
889 pwallet->MarkDirty();
901 // Try to (very carefully!) recover wallet.dat if there is a problem.
903 bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
905 // Recovery procedure:
906 // move wallet.dat to wallet.timestamp.bak
907 // Call Salvage with fAggressive=true to
908 // get as much data as possible.
909 // Rewrite salvaged data to wallet.dat
910 // Set -rescan so any missing transactions will be
912 int64_t now = GetTime();
913 std::string newFilename = strprintf("wallet.%" PRId64 ".bak", now);
915 int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
916 newFilename.c_str(), DB_AUTO_COMMIT);
918 printf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str());
921 printf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str());
925 std::vector<CDBEnv::KeyValPair> salvagedData;
926 bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
927 if (salvagedData.empty())
929 printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
932 printf("Salvage(aggressive) found %" PRIszu " records\n", salvagedData.size());
934 bool fSuccess = allOK;
935 Db* pdbCopy = new Db(&dbenv.dbenv, 0);
936 int ret = pdbCopy->open(NULL, // Txn pointer
937 filename.c_str(), // Filename
938 "main", // Logical db name
939 DB_BTREE, // Database type
944 printf("Cannot create database file %s\n", filename.c_str());
948 CWalletScanState wss;
950 DbTxn* ptxn = dbenv.TxnBegin();
951 BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
955 CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
956 CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
957 string strType, strErr;
958 bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
959 wss, strType, strErr);
960 if (!IsKeyType(strType))
964 printf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str());
968 Dbt datKey(&row.first[0], row.first.size());
969 Dbt datValue(&row.second[0], row.second.size());
970 int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
981 bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
983 return CWalletDB::Recover(dbenv, filename, false);