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/filesystem.hpp>
11 using namespace boost;
14 static uint64 nAccountingEntryNumber = 0;
15 extern bool fWalletUnlockMintOnly;
21 bool CWalletDB::WriteName(const string& strAddress, const string& strName)
24 return Write(make_pair(string("name"), strAddress), strName);
27 bool CWalletDB::EraseName(const string& strAddress)
29 // This should only be used for sending addresses, never for receiving addresses,
30 // receiving addresses must always have an address book entry if they're not change return.
32 return Erase(make_pair(string("name"), strAddress));
35 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
38 return Read(make_pair(string("acc"), strAccount), account);
41 bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
43 return Write(make_pair(string("acc"), strAccount), account);
46 bool CWalletDB::WriteAccountingEntry(const uint64 nAccEntryNum, const CAccountingEntry& acentry)
48 return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
51 bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
53 return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
56 int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
58 list<CAccountingEntry> entries;
59 ListAccountCreditDebit(strAccount, entries);
61 int64 nCreditDebit = 0;
62 BOOST_FOREACH (const CAccountingEntry& entry, entries)
63 nCreditDebit += entry.nCreditDebit;
68 void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
70 bool fAllAccounts = (strAccount == "*");
72 Dbc* pcursor = GetCursor();
74 throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
75 unsigned int fFlags = DB_SET_RANGE;
79 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
80 if (fFlags == DB_SET_RANGE)
81 ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
82 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
83 int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
85 if (ret == DB_NOTFOUND)
90 throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
96 if (strType != "acentry")
98 CAccountingEntry acentry;
99 ssKey >> acentry.strAccount;
100 if (!fAllAccounts && acentry.strAccount != strAccount)
104 ssKey >> acentry.nEntryNo;
105 entries.push_back(acentry);
113 CWalletDB::ReorderTransactions(CWallet* pwallet)
115 LOCK(pwallet->cs_wallet);
116 // Old wallets didn't have any defined order for transactions
117 // Probably a bad idea to change the output of this
119 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
120 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
121 typedef multimap<int64, TxPair > TxItems;
124 for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
126 CWalletTx* wtx = &((*it).second);
127 txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
129 list<CAccountingEntry> acentries;
130 ListAccountCreditDebit("", acentries);
131 BOOST_FOREACH(CAccountingEntry& entry, acentries)
133 txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
136 int64& nOrderPosNext = pwallet->nOrderPosNext;
138 std::vector<int64> nOrderPosOffsets;
139 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
141 CWalletTx *const pwtx = (*it).second.first;
142 CAccountingEntry *const pacentry = (*it).second.second;
143 int64& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
147 nOrderPos = nOrderPosNext++;
148 nOrderPosOffsets.push_back(nOrderPos);
151 // Have to write accounting regardless, since we don't keep it in memory
152 if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
157 int64 nOrderPosOff = 0;
158 BOOST_FOREACH(const int64& nOffsetStart, nOrderPosOffsets)
160 if (nOrderPos >= nOffsetStart)
163 nOrderPos += nOrderPosOff;
164 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
169 // Since we're changing the order, write it back
172 if (!WriteTx(pwtx->GetHash(), *pwtx))
176 if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
184 class CWalletScanState {
188 unsigned int nKeyMeta;
192 vector<uint256> vWalletUpgrade;
195 nKeys = nCKeys = nKeyMeta = 0;
196 fIsEncrypted = false;
197 fAnyUnordered = false;
203 ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
204 CWalletScanState &wss, string& strType, string& strErr)
208 // Taking advantage of the fact that pair serialization
209 // is just the two items serialized one after the other
211 if (strType == "name")
215 ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()];
217 else if (strType == "tx")
221 CWalletTx& wtx = pwallet->mapWallet[hash];
223 if (wtx.CheckTransaction() && (wtx.GetHash() == hash))
224 wtx.BindWallet(pwallet);
227 pwallet->mapWallet.erase(hash);
231 // Undo serialize changes in 31600
232 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
234 if (!ssValue.empty())
238 ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
239 strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
240 wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
241 wtx.fTimeReceivedIsTxTime = fTmp;
245 strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
246 wtx.fTimeReceivedIsTxTime = 0;
248 wss.vWalletUpgrade.push_back(hash);
251 if (wtx.nOrderPos == -1)
252 wss.fAnyUnordered = true;
255 //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
256 //printf(" %12"PRI64d" %s %s %s\n",
257 // wtx.vout[0].nValue,
258 // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
259 // wtx.hashBlock.ToString().substr(0,20).c_str(),
260 // wtx.mapValue["message"].c_str());
262 else if (strType == "acentry")
268 if (nNumber > nAccountingEntryNumber)
269 nAccountingEntryNumber = nNumber;
271 if (!wss.fAnyUnordered)
273 CAccountingEntry acentry;
275 if (acentry.nOrderPos == -1)
276 wss.fAnyUnordered = true;
279 else if (strType == "key" || strType == "wkey")
281 vector<unsigned char> vchPubKey;
284 if (strType == "key")
289 key.SetPubKey(vchPubKey);
290 if (!key.SetPrivKey(pkey))
292 strErr = "Error reading wallet database: CPrivKey corrupt";
295 if (key.GetPubKey() != vchPubKey)
297 strErr = "Error reading wallet database: CPrivKey pubkey inconsistency";
302 strErr = "Error reading wallet database: invalid CPrivKey";
310 key.SetPubKey(vchPubKey);
311 if (!key.SetPrivKey(wkey.vchPrivKey))
313 strErr = "Error reading wallet database: CPrivKey corrupt";
316 if (key.GetPubKey() != vchPubKey)
318 strErr = "Error reading wallet database: CWalletKey pubkey inconsistency";
323 strErr = "Error reading wallet database: invalid CWalletKey";
327 if (!pwallet->LoadKey(key))
329 strErr = "Error reading wallet database: LoadKey failed";
333 else if (strType == "mkey")
337 CMasterKey kMasterKey;
338 ssValue >> kMasterKey;
339 if(pwallet->mapMasterKeys.count(nID) != 0)
341 strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
344 pwallet->mapMasterKeys[nID] = kMasterKey;
345 if (pwallet->nMasterKeyMaxID < nID)
346 pwallet->nMasterKeyMaxID = nID;
348 else if (strType == "ckey")
351 vector<unsigned char> vchPubKey;
353 vector<unsigned char> vchPrivKey;
354 ssValue >> vchPrivKey;
355 if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
357 strErr = "Error reading wallet database: LoadCryptedKey failed";
360 wss.fIsEncrypted = true;
362 else if (strType == "keymeta")
366 CKeyMetadata keyMeta;
370 pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
372 // find earliest key creation time, as wallet birthday
373 if (!pwallet->nTimeFirstKey ||
374 (keyMeta.nCreateTime < pwallet->nTimeFirstKey))
375 pwallet->nTimeFirstKey = keyMeta.nCreateTime;
377 else if (strType == "defaultkey")
379 ssValue >> pwallet->vchDefaultKey;
381 else if (strType == "pool")
387 pwallet->setKeyPool.insert(nIndex);
389 // If no metadata exists yet, create a default with the pool key's
390 // creation time. Note that this may be overwritten by actually
391 // stored metadata for that key later, which is fine.
392 CKeyID keyid = keypool.vchPubKey.GetID();
393 if (pwallet->mapKeyMetadata.count(keyid) == 0)
394 pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
397 else if (strType == "version")
399 ssValue >> wss.nFileVersion;
400 if (wss.nFileVersion == 10300)
401 wss.nFileVersion = 300;
403 else if (strType == "cscript")
409 if (!pwallet->LoadCScript(script))
411 strErr = "Error reading wallet database: LoadCScript failed";
415 else if (strType == "orderposnext")
417 ssValue >> pwallet->nOrderPosNext;
426 static bool IsKeyType(string strType)
428 return (strType== "key" || strType == "wkey" ||
429 strType == "mkey" || strType == "ckey");
432 DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
434 pwallet->vchDefaultKey = CPubKey();
435 CWalletScanState wss;
436 bool fNoncriticalErrors = false;
437 DBErrors result = DB_LOAD_OK;
440 LOCK(pwallet->cs_wallet);
442 if (Read((string)"minversion", nMinVersion))
444 if (nMinVersion > CLIENT_VERSION)
446 pwallet->LoadMinVersion(nMinVersion);
450 Dbc* pcursor = GetCursor();
453 printf("Error getting wallet database cursor\n");
460 CDataStream ssKey(SER_DISK, CLIENT_VERSION);
461 CDataStream ssValue(SER_DISK, CLIENT_VERSION);
462 int ret = ReadAtCursor(pcursor, ssKey, ssValue);
463 if (ret == DB_NOTFOUND)
467 printf("Error reading next record from wallet database\n");
471 // Try to be tolerant of single corrupt records:
472 string strType, strErr;
473 if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
475 // losing keys is considered a catastrophic error, anything else
476 // we assume the user can live with:
477 if (IsKeyType(strType))
481 // Leave other errors alone, if we try to fix them we might make things worse.
482 fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
484 // Rescan if there is a bad transaction record:
485 SoftSetBoolArg("-rescan", true);
489 printf("%s\n", strErr.c_str());
498 if (fNoncriticalErrors && result == DB_LOAD_OK)
499 result = DB_NONCRITICAL_ERROR;
501 // Any wallet corruption at all: skip any rewriting or
502 // upgrading, we don't want to make it worse.
503 if (result != DB_LOAD_OK)
506 printf("nFileVersion = %d\n", wss.nFileVersion);
508 printf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
509 wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
511 // nTimeFirstKey is only reliable if all keys have metadata
512 if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
513 pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
516 BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
517 WriteTx(hash, pwallet->mapWallet[hash]);
519 // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
520 if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
521 return DB_NEED_REWRITE;
523 if (wss.nFileVersion < CLIENT_VERSION) // Update
524 WriteVersion(CLIENT_VERSION);
526 if (wss.fAnyUnordered)
527 result = ReorderTransactions(pwallet);
532 void ThreadFlushWalletDB(void* parg)
534 // Make this thread recognisable as the wallet flushing thread
535 RenameThread("bitcoin-wallet");
537 const string& strFile = ((const string*)parg)[0];
538 static bool fOneThread;
542 if (!GetBoolArg("-flushwallet", true))
545 unsigned int nLastSeen = nWalletDBUpdated;
546 unsigned int nLastFlushed = nWalletDBUpdated;
547 int64 nLastWalletUpdate = GetTime();
552 if (nLastSeen != nWalletDBUpdated)
554 nLastSeen = nWalletDBUpdated;
555 nLastWalletUpdate = GetTime();
558 if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
560 TRY_LOCK(bitdb.cs_db,lockDb);
563 // Don't do this if any databases are in use
565 map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
566 while (mi != bitdb.mapFileUseCount.end())
568 nRefCount += (*mi).second;
572 if (nRefCount == 0 && !fShutdown)
574 map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
575 if (mi != bitdb.mapFileUseCount.end())
577 printf("Flushing wallet.dat\n");
578 nLastFlushed = nWalletDBUpdated;
579 int64 nStart = GetTimeMillis();
581 // Flush wallet.dat so it's self contained
582 bitdb.CloseDb(strFile);
583 bitdb.CheckpointLSN(strFile);
585 bitdb.mapFileUseCount.erase(mi++);
586 printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
594 bool BackupWallet(const CWallet& wallet, const string& strDest)
596 if (!wallet.fFileBacked)
602 if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
604 // Flush log data to the dat file
605 bitdb.CloseDb(wallet.strWalletFile);
606 bitdb.CheckpointLSN(wallet.strWalletFile);
607 bitdb.mapFileUseCount.erase(wallet.strWalletFile);
610 filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
611 filesystem::path pathDest(strDest);
612 if (filesystem::is_directory(pathDest))
613 pathDest /= wallet.strWalletFile;
616 #if BOOST_VERSION >= 104000
617 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
619 filesystem::copy_file(pathSrc, pathDest);
621 printf("copied wallet.dat to %s\n", pathDest.string().c_str());
623 } catch(const filesystem::filesystem_error &e) {
624 printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
635 // Try to (very carefully!) recover wallet.dat if there is a problem.
637 bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
639 // Recovery procedure:
640 // move wallet.dat to wallet.timestamp.bak
641 // Call Salvage with fAggressive=true to
642 // get as much data as possible.
643 // Rewrite salvaged data to wallet.dat
644 // Set -rescan so any missing transactions will be
646 int64 now = GetTime();
647 std::string newFilename = strprintf("wallet.%"PRI64d".bak", now);
649 int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
650 newFilename.c_str(), DB_AUTO_COMMIT);
652 printf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str());
655 printf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str());
659 std::vector<CDBEnv::KeyValPair> salvagedData;
660 bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
661 if (salvagedData.empty())
663 printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
666 printf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size());
668 bool fSuccess = allOK;
669 Db* pdbCopy = new Db(&dbenv.dbenv, 0);
670 int ret = pdbCopy->open(NULL, // Txn pointer
671 filename.c_str(), // Filename
672 "main", // Logical db name
673 DB_BTREE, // Database type
678 printf("Cannot create database file %s\n", filename.c_str());
682 CWalletScanState wss;
684 DbTxn* ptxn = dbenv.TxnBegin();
685 BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
689 CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
690 CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
691 string strType, strErr;
692 bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
693 wss, strType, strErr);
694 if (!IsKeyType(strType))
698 printf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str());
702 Dbt datKey(&row.first[0], row.first.size());
703 Dbt datValue(&row.second[0], row.second.size());
704 int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
715 bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
717 return CWalletDB::Recover(dbenv, filename, false);