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.
8 #include <boost/version.hpp>
9 #include <boost/filesystem.hpp>
12 using namespace boost;
15 static uint64 nAccountingEntryNumber = 0;
16 extern bool fWalletUnlockMintOnly;
22 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
25 return Write(make_pair(string("name"), strAddress), strName);
28 bool CWalletDB::EraseName(const string& strAddress)
30 // This should only be used for sending addresses, never for receiving addresses,
31 // receiving addresses must always have an address book entry if they're not change return.
33 return Erase(make_pair(string("name"), strAddress));
36 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
39 return Read(make_pair(string("acc"), strAccount), account);
42 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
44 return Write(make_pair(string("acc"), strAccount), account);
47 bool CWalletDB::WriteAccountingEntry(const uint64 nAccEntryNum, const CAccountingEntry& acentry)
49 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
52 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
54 return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
57 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
59 list<CAccountingEntry> entries;
60 ListAccountCreditDebit(strAccount, entries);
62 int64 nCreditDebit = 0;
63 BOOST_FOREACH (const CAccountingEntry& entry, entries)
64 nCreditDebit += entry.nCreditDebit;
69 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
71 bool fAllAccounts = (strAccount == "*");
73 Dbc* pcursor = GetCursor();
75 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
76 unsigned int fFlags = DB_SET_RANGE;
80 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
81 if (fFlags == DB_SET_RANGE)
82 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
83 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
84 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
86 if (ret == DB_NOTFOUND)
91 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
97 if (strType != "acentry")
99 CAccountingEntry acentry;
100 ssKey >> acentry.strAccount;
101 if (!fAllAccounts && acentry.strAccount != strAccount)
105 ssKey >> acentry.nEntryNo;
106 entries.push_back(acentry);
114 CWalletDB::ReorderTransactions(CWallet* pwallet)
116 LOCK(pwallet->cs_wallet);
117 // Old wallets didn't have any defined order for transactions
118 // Probably a bad idea to change the output of this
120 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
121 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
122 typedef multimap<int64, TxPair > TxItems;
125 for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
127 CWalletTx* wtx = &((*it).second);
128 txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
130 list<CAccountingEntry> acentries;
131 ListAccountCreditDebit("", acentries);
132 BOOST_FOREACH(CAccountingEntry& entry, acentries)
134 txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
137 int64& nOrderPosNext = pwallet->nOrderPosNext;
139 std::vector<int64> nOrderPosOffsets;
140 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
142 CWalletTx *const pwtx = (*it).second.first;
143 CAccountingEntry *const pacentry = (*it).second.second;
144 int64& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
148 nOrderPos = nOrderPosNext++;
149 nOrderPosOffsets.push_back(nOrderPos);
152 // Have to write accounting regardless, since we don't keep it in memory
153 if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
158 int64 nOrderPosOff = 0;
159 BOOST_FOREACH(const int64& nOffsetStart, nOrderPosOffsets)
161 if (nOrderPos >= nOffsetStart)
164 nOrderPos += nOrderPosOff;
165 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
170 // Since we're changing the order, write it back
173 if (!WriteTx(pwtx->GetHash(), *pwtx))
177 if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
185 class CWalletScanState {
189 unsigned int nKeyMeta;
193 vector<uint256> vWalletUpgrade;
196 nKeys = nCKeys = nKeyMeta = 0;
197 fIsEncrypted = false;
198 fAnyUnordered = false;
204 ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
205 CWalletScanState &wss, string& strType, string& strErr)
209 // Taking advantage of the fact that pair serialization
210 // is just the two items serialized one after the other
212 if (strType == "name")
216 ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()];
218 else if (strType == "tx")
222 CWalletTx& wtx = pwallet->mapWallet[hash];
224 if (wtx.CheckTransaction() && (wtx.GetHash() == hash))
225 wtx.BindWallet(pwallet);
228 pwallet->mapWallet.erase(hash);
232 // Undo serialize changes in 31600
233 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
235 if (!ssValue.empty())
239 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
240 strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
241 wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
242 wtx.fTimeReceivedIsTxTime = fTmp;
246 strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
247 wtx.fTimeReceivedIsTxTime = 0;
249 wss.vWalletUpgrade.push_back(hash);
252 if (wtx.nOrderPos == -1)
253 wss.fAnyUnordered = true;
256 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
257 //printf(" %12"PRI64d" %s %s %s\n",
258 // wtx.vout[0].nValue,
259 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
260 // wtx.hashBlock.ToString().substr(0,20).c_str(),
261 // wtx.mapValue["message"].c_str());
263 else if (strType == "acentry")
269 if (nNumber > nAccountingEntryNumber)
270 nAccountingEntryNumber = nNumber;
272 if (!wss.fAnyUnordered)
274 CAccountingEntry acentry;
276 if (acentry.nOrderPos == -1)
277 wss.fAnyUnordered = true;
280 else if (strType == "key" || strType == "wkey")
282 vector<unsigned char> vchPubKey;
285 if (strType == "key")
290 key.SetPubKey(vchPubKey);
291 if (!key.SetPrivKey(pkey))
293 strErr = "Error reading wallet database: CPrivKey corrupt";
296 if (key.GetPubKey() != vchPubKey)
298 strErr = "Error reading wallet database: CPrivKey pubkey inconsistency";
303 strErr = "Error reading wallet database: invalid CPrivKey";
311 key.SetPubKey(vchPubKey);
312 if (!key.SetPrivKey(wkey.vchPrivKey))
314 strErr = "Error reading wallet database: CPrivKey corrupt";
317 if (key.GetPubKey() != vchPubKey)
319 strErr = "Error reading wallet database: CWalletKey pubkey inconsistency";
324 strErr = "Error reading wallet database: invalid CWalletKey";
328 if (!pwallet->LoadKey(key))
330 strErr = "Error reading wallet database: LoadKey failed";
334 else if (strType == "mkey")
338 CMasterKey kMasterKey;
339 ssValue >> kMasterKey;
340 if(pwallet->mapMasterKeys.count(nID) != 0)
342 strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
345 pwallet->mapMasterKeys[nID] = kMasterKey;
346 if (pwallet->nMasterKeyMaxID < nID)
347 pwallet->nMasterKeyMaxID = nID;
349 else if (strType == "ckey")
352 vector<unsigned char> vchPubKey;
354 vector<unsigned char> vchPrivKey;
355 ssValue >> vchPrivKey;
356 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
358 strErr = "Error reading wallet database: LoadCryptedKey failed";
361 wss.fIsEncrypted = true;
363 else if (strType == "keymeta")
367 CKeyMetadata keyMeta;
371 pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
373 // find earliest key creation time, as wallet birthday
374 if (!pwallet->nTimeFirstKey ||
375 (keyMeta.nCreateTime < pwallet->nTimeFirstKey))
376 pwallet->nTimeFirstKey = keyMeta.nCreateTime;
378 else if (strType == "defaultkey")
380 ssValue >> pwallet->vchDefaultKey;
382 else if (strType == "pool")
388 pwallet->setKeyPool.insert(nIndex);
390 // If no metadata exists yet, create a default with the pool key's
391 // creation time. Note that this may be overwritten by actually
392 // stored metadata for that key later, which is fine.
393 CKeyID keyid = keypool.vchPubKey.GetID();
394 if (pwallet->mapKeyMetadata.count(keyid) == 0)
395 pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
398 else if (strType == "version")
400 ssValue >> wss.nFileVersion;
401 if (wss.nFileVersion == 10300)
402 wss.nFileVersion = 300;
404 else if (strType == "cscript")
410 if (!pwallet->LoadCScript(script))
412 strErr = "Error reading wallet database: LoadCScript failed";
416 else if (strType == "orderposnext")
418 ssValue >> pwallet->nOrderPosNext;
427 static bool IsKeyType(string strType)
429 return (strType== "key" || strType == "wkey" ||
430 strType == "mkey" || strType == "ckey");
433 DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
435 pwallet->vchDefaultKey = CPubKey();
436 CWalletScanState wss;
437 bool fNoncriticalErrors = false;
438 DBErrors result = DB_LOAD_OK;
441 LOCK(pwallet->cs_wallet);
443 if (Read((string)"minversion", nMinVersion))
445 if (nMinVersion > CLIENT_VERSION)
447 pwallet->LoadMinVersion(nMinVersion);
451 Dbc* pcursor = GetCursor();
454 printf("Error getting wallet database cursor\n");
461 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
462 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
463 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
464 if (ret == DB_NOTFOUND)
468 printf("Error reading next record from wallet database\n");
472 // Try to be tolerant of single corrupt records:
473 string strType, strErr;
474 if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
476 // losing keys is considered a catastrophic error, anything else
477 // we assume the user can live with:
478 if (IsKeyType(strType))
482 // Leave other errors alone, if we try to fix them we might make things worse.
483 fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
485 // Rescan if there is a bad transaction record:
486 SoftSetBoolArg("-rescan", true);
490 printf("%s\n", strErr.c_str());
499 if (fNoncriticalErrors && result == DB_LOAD_OK)
500 result = DB_NONCRITICAL_ERROR;
502 // Any wallet corruption at all: skip any rewriting or
503 // upgrading, we don't want to make it worse.
504 if (result != DB_LOAD_OK)
507 printf("nFileVersion = %d\n", wss.nFileVersion);
509 printf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
510 wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
512 // nTimeFirstKey is only reliable if all keys have metadata
513 if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
514 pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
517 BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
518 WriteTx(hash, pwallet->mapWallet[hash]);
520 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
521 if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
522 return DB_NEED_REWRITE;
524 if (wss.nFileVersion < CLIENT_VERSION) // Update
525 WriteVersion(CLIENT_VERSION);
527 if (wss.fAnyUnordered)
528 result = ReorderTransactions(pwallet);
533 void ThreadFlushWalletDB(void* parg)
535 // Make this thread recognisable as the wallet flushing thread
536 RenameThread("bitcoin-wallet");
538 const string& strFile = ((const string*)parg)[0];
539 static bool fOneThread;
543 if (!GetBoolArg("-flushwallet", true))
546 unsigned int nLastSeen = nWalletDBUpdated;
547 unsigned int nLastFlushed = nWalletDBUpdated;
548 int64 nLastWalletUpdate = GetTime();
553 if (nLastSeen != nWalletDBUpdated)
555 nLastSeen = nWalletDBUpdated;
556 nLastWalletUpdate = GetTime();
559 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
561 TRY_LOCK(bitdb.cs_db,lockDb);
564 // Don't do this if any databases are in use
566 map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
567 while (mi != bitdb.mapFileUseCount.end())
569 nRefCount += (*mi).second;
573 if (nRefCount == 0 && !fShutdown)
575 map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
576 if (mi != bitdb.mapFileUseCount.end())
578 printf("Flushing wallet.dat\n");
579 nLastFlushed = nWalletDBUpdated;
580 int64 nStart = GetTimeMillis();
582 // Flush wallet.dat so it's self contained
583 bitdb.CloseDb(strFile);
584 bitdb.CheckpointLSN(strFile);
586 bitdb.mapFileUseCount.erase(mi++);
587 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
595 bool BackupWallet(const CWallet& wallet, const string& strDest)
597 if (!wallet.fFileBacked)
603 if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
605 // Flush log data to the dat file
606 bitdb.CloseDb(wallet.strWalletFile);
607 bitdb.CheckpointLSN(wallet.strWalletFile);
608 bitdb.mapFileUseCount.erase(wallet.strWalletFile);
611 filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
612 filesystem::path pathDest(strDest);
613 if (filesystem::is_directory(pathDest))
614 pathDest /= wallet.strWalletFile;
617 #if BOOST_VERSION >= 104000
618 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
620 filesystem::copy_file(pathSrc, pathDest);
622 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
624 } catch(const filesystem::filesystem_error &e) {
625 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
636 // Try to (very carefully!) recover wallet.dat if there is a problem.
638 bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
640 // Recovery procedure:
641 // move wallet.dat to wallet.timestamp.bak
642 // Call Salvage with fAggressive=true to
643 // get as much data as possible.
644 // Rewrite salvaged data to wallet.dat
645 // Set -rescan so any missing transactions will be
647 int64 now = GetTime();
648 std::string newFilename = strprintf("wallet.%"PRI64d".bak", now);
650 int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
651 newFilename.c_str(), DB_AUTO_COMMIT);
653 printf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str());
656 printf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str());
660 std::vector<CDBEnv::KeyValPair> salvagedData;
661 bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
662 if (salvagedData.empty())
664 printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
667 printf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size());
669 bool fSuccess = allOK;
670 Db* pdbCopy = new Db(&dbenv.dbenv, 0);
671 int ret = pdbCopy->open(NULL, // Txn pointer
672 filename.c_str(), // Filename
673 "main", // Logical db name
674 DB_BTREE, // Database type
679 printf("Cannot create database file %s\n", filename.c_str());
683 CWalletScanState wss;
685 DbTxn* ptxn = dbenv.TxnBegin();
686 BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
690 CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
691 CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
692 string strType, strErr;
693 bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
694 wss, strType, strErr);
695 if (!IsKeyType(strType))
699 printf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str());
703 Dbt datKey(&row.first[0], row.first.size());
704 Dbt datValue(&row.second[0], row.second.size());
705 int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
716 bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
718 return CWalletDB::Recover(dbenv, filename, false);