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.
5 #ifndef BITCOIN_WALLET_H
6 #define BITCOIN_WALLET_H
16 // A CWallet is an extension of a keystore, which also maintains a set of
17 // transactions and balances, and provides the ability to create new
19 class CWallet : public CCryptoKeyStore
22 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
23 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
25 CWalletDB *pwalletdbEncryption;
28 mutable CCriticalSection cs_wallet;
31 std::string strWalletFile;
33 std::set<int64> setKeyPool;
35 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
36 MasterKeyMap mapMasterKeys;
37 unsigned int nMasterKeyMaxID;
43 pwalletdbEncryption = NULL;
45 CWallet(std::string strWalletFileIn)
47 strWalletFile = strWalletFileIn;
50 pwalletdbEncryption = NULL;
53 std::map<uint256, CWalletTx> mapWallet;
54 std::vector<uint256> vWalletUpdated;
56 std::map<uint256, int> mapRequestCount;
58 std::map<CBitcoinAddress, std::string> mapAddressBook;
60 std::vector<unsigned char> vchDefaultKey;
62 // keystore implementation
63 // Adds a key to the store, and saves it to disk.
64 bool AddKey(const CKey& key);
65 // Adds a key to the store, without saving it to disk (used by LoadWallet)
66 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
68 // Adds an encrypted key to the store, and saves it to disk.
69 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
70 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
71 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
73 bool Unlock(const SecureString& strWalletPassphrase);
74 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
75 bool EncryptWallet(const SecureString& strWalletPassphrase);
77 bool AddToWallet(const CWalletTx& wtxIn);
78 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
79 bool EraseFromWallet(uint256 hash);
80 void WalletUpdateSpent(const CTransaction& prevout);
81 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
82 void ReacceptWalletTransactions();
83 void ResendWalletTransactions();
84 int64 GetBalance() const;
85 int64 GetUnconfirmedBalance() const;
86 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
87 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
88 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
89 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
90 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
94 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
95 void KeepKey(int64 nIndex);
96 void ReturnKey(int64 nIndex);
97 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
98 int64 GetOldestKeyPoolTime();
100 bool IsMine(const CTxIn& txin) const;
101 int64 GetDebit(const CTxIn& txin) const;
102 bool IsMine(const CTxOut& txout) const
104 return ::IsMine(*this, txout.scriptPubKey);
106 int64 GetCredit(const CTxOut& txout) const
108 if (!MoneyRange(txout.nValue))
109 throw std::runtime_error("CWallet::GetCredit() : value out of range");
110 return (IsMine(txout) ? txout.nValue : 0);
112 bool IsChange(const CTxOut& txout) const
114 CBitcoinAddress address;
115 if (ExtractAddress(txout.scriptPubKey, this, address))
116 CRITICAL_BLOCK(cs_wallet)
117 if (!mapAddressBook.count(address))
121 int64 GetChange(const CTxOut& txout) const
123 if (!MoneyRange(txout.nValue))
124 throw std::runtime_error("CWallet::GetChange() : value out of range");
125 return (IsChange(txout) ? txout.nValue : 0);
127 bool IsMine(const CTransaction& tx) const
129 BOOST_FOREACH(const CTxOut& txout, tx.vout)
134 bool IsFromMe(const CTransaction& tx) const
136 return (GetDebit(tx) > 0);
138 int64 GetDebit(const CTransaction& tx) const
141 BOOST_FOREACH(const CTxIn& txin, tx.vin)
143 nDebit += GetDebit(txin);
144 if (!MoneyRange(nDebit))
145 throw std::runtime_error("CWallet::GetDebit() : value out of range");
149 int64 GetCredit(const CTransaction& tx) const
152 BOOST_FOREACH(const CTxOut& txout, tx.vout)
154 nCredit += GetCredit(txout);
155 if (!MoneyRange(nCredit))
156 throw std::runtime_error("CWallet::GetCredit() : value out of range");
160 int64 GetChange(const CTransaction& tx) const
163 BOOST_FOREACH(const CTxOut& txout, tx.vout)
165 nChange += GetChange(txout);
166 if (!MoneyRange(nChange))
167 throw std::runtime_error("CWallet::GetChange() : value out of range");
171 void SetBestChain(const CBlockLocator& loc)
173 CWalletDB walletdb(strWalletFile);
174 walletdb.WriteBestBlock(loc);
177 int LoadWallet(bool& fFirstRunRet);
178 // bool BackupWallet(const std::string& strDest);
180 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
182 bool DelAddressBookName(const CBitcoinAddress& address);
184 void UpdatedTransaction(const uint256 &hashTx)
186 CRITICAL_BLOCK(cs_wallet)
187 vWalletUpdated.push_back(hashTx);
190 void PrintWallet(const CBlock& block);
192 void Inventory(const uint256 &hash)
194 CRITICAL_BLOCK(cs_wallet)
196 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
197 if (mi != mapRequestCount.end())
204 return setKeyPool.size();
207 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
209 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
218 std::vector<unsigned char> vchPubKey;
220 CReserveKey(CWallet* pwalletIn)
233 std::vector<unsigned char> GetReservedKey();
239 // A transaction with a bunch of additional info that only the owner cares
240 // about. It includes any unrecorded transactions needed to link it back
241 // to the block chain.
243 class CWalletTx : public CMerkleTx
246 const CWallet* pwallet;
248 std::vector<CMerkleTx> vtxPrev;
249 std::map<std::string, std::string> mapValue;
250 std::vector<std::pair<std::string, std::string> > vOrderForm;
251 unsigned int fTimeReceivedIsTxTime;
252 unsigned int nTimeReceived; // time received by this node
254 std::string strFromAccount;
255 std::vector<char> vfSpent; // which outputs are already spent
258 mutable char fDebitCached;
259 mutable char fCreditCached;
260 mutable char fAvailableCreditCached;
261 mutable char fChangeCached;
262 mutable int64 nDebitCached;
263 mutable int64 nCreditCached;
264 mutable int64 nAvailableCreditCached;
265 mutable int64 nChangeCached;
267 // memory only UI hints
268 mutable unsigned int nTimeDisplayed;
269 mutable int nLinesDisplayed;
270 mutable char fConfirmedDisplayed;
277 CWalletTx(const CWallet* pwalletIn)
282 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
287 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
292 void Init(const CWallet* pwalletIn)
298 fTimeReceivedIsTxTime = false;
301 strFromAccount.clear();
303 fDebitCached = false;
304 fCreditCached = false;
305 fAvailableCreditCached = false;
306 fChangeCached = false;
309 nAvailableCreditCached = 0;
313 fConfirmedDisplayed = false;
318 CWalletTx* pthis = const_cast<CWalletTx*>(this);
325 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
328 BOOST_FOREACH(char f, vfSpent)
330 str += (f ? '1' : '0');
334 pthis->mapValue["spent"] = str;
337 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
340 READWRITE(vOrderForm);
341 READWRITE(fTimeReceivedIsTxTime);
342 READWRITE(nTimeReceived);
348 pthis->strFromAccount = pthis->mapValue["fromaccount"];
350 if (mapValue.count("spent"))
351 BOOST_FOREACH(char c, pthis->mapValue["spent"])
352 pthis->vfSpent.push_back(c != '0');
354 pthis->vfSpent.assign(vout.size(), fSpent);
357 pthis->mapValue.erase("fromaccount");
358 pthis->mapValue.erase("version");
359 pthis->mapValue.erase("spent");
362 // marks certain txout's as spent
363 // returns true if any update took place
364 bool UpdateSpent(const std::vector<char>& vfNewSpent)
366 bool fReturn = false;
367 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
369 if (i == vfSpent.size())
372 if (vfNewSpent[i] && !vfSpent[i])
376 fAvailableCreditCached = false;
382 // make sure balances are recalculated
385 fCreditCached = false;
386 fAvailableCreditCached = false;
387 fDebitCached = false;
388 fChangeCached = false;
391 void MarkSpent(unsigned int nOut)
393 if (nOut >= vout.size())
394 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
395 vfSpent.resize(vout.size());
398 vfSpent[nOut] = true;
399 fAvailableCreditCached = false;
403 bool IsSpent(unsigned int nOut) const
405 if (nOut >= vout.size())
406 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
407 if (nOut >= vfSpent.size())
409 return (!!vfSpent[nOut]);
412 int64 GetDebit() const
418 nDebitCached = pwallet->GetDebit(*this);
423 int64 GetCredit(bool fUseCache=true) const
425 // Must wait until coinbase is safely deep enough in the chain before valuing it
426 if (IsCoinBase() && GetBlocksToMaturity() > 0)
429 // GetBalance can assume transactions in mapWallet won't change
430 if (fUseCache && fCreditCached)
431 return nCreditCached;
432 nCreditCached = pwallet->GetCredit(*this);
433 fCreditCached = true;
434 return nCreditCached;
437 int64 GetAvailableCredit(bool fUseCache=true) const
439 // Must wait until coinbase is safely deep enough in the chain before valuing it
440 if (IsCoinBase() && GetBlocksToMaturity() > 0)
443 if (fUseCache && fAvailableCreditCached)
444 return nAvailableCreditCached;
447 for (unsigned int i = 0; i < vout.size(); i++)
451 const CTxOut &txout = vout[i];
452 nCredit += pwallet->GetCredit(txout);
453 if (!MoneyRange(nCredit))
454 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
458 nAvailableCreditCached = nCredit;
459 fAvailableCreditCached = true;
464 int64 GetChange() const
467 return nChangeCached;
468 nChangeCached = pwallet->GetChange(*this);
469 fChangeCached = true;
470 return nChangeCached;
473 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
474 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
476 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
477 int64& nSent, int64& nFee) const;
479 bool IsFromMe() const
481 return (GetDebit() > 0);
484 bool IsConfirmed() const
486 // Quick answer in most cases
489 if (GetDepthInMainChain() >= 1)
491 if (!IsFromMe()) // using wtx's cached debit
494 // If no confirmations but it's from us, we can still
495 // consider it confirmed if all dependencies are confirmed
496 std::map<uint256, const CMerkleTx*> mapPrev;
497 std::vector<const CMerkleTx*> vWorkQueue;
498 vWorkQueue.reserve(vtxPrev.size()+1);
499 vWorkQueue.push_back(this);
500 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
502 const CMerkleTx* ptx = vWorkQueue[i];
506 if (ptx->GetDepthInMainChain() >= 1)
508 if (!pwallet->IsFromMe(*ptx))
513 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
514 mapPrev[tx.GetHash()] = &tx;
517 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
519 if (!mapPrev.count(txin.prevout.hash))
521 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
529 int64 GetTxTime() const;
530 int GetRequestCount() const;
532 void AddSupportingTransactions(CTxDB& txdb);
534 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
535 bool AcceptWalletTransaction();
537 void RelayWalletTransaction(CTxDB& txdb);
538 void RelayWalletTransaction();
543 // Private key that includes an expiration date in case it never gets used.
551 std::string strComment;
552 //// todo: add something to note what created it (user, getnewaddress, change)
553 //// maybe should have a map<string, string> property map
555 CWalletKey(int64 nExpires=0)
557 nTimeCreated = (nExpires ? GetTime() : 0);
558 nTimeExpires = nExpires;
563 if (!(nType & SER_GETHASH))
565 READWRITE(vchPrivKey);
566 READWRITE(nTimeCreated);
567 READWRITE(nTimeExpires);
568 READWRITE(strComment);
578 // Account information.
579 // Stored in wallet with key "acc"+string account name
584 std::vector<unsigned char> vchPubKey;
598 if (!(nType & SER_GETHASH))
600 READWRITE(vchPubKey);
607 // Internal transfers.
608 // Database key is acentry<account><counter>
610 class CAccountingEntry
613 std::string strAccount;
616 std::string strOtherAccount;
617 std::string strComment;
629 strOtherAccount.clear();
635 if (!(nType & SER_GETHASH))
637 // Note: strAccount is serialized as part of the key, not here.
638 READWRITE(nCreditDebit);
640 READWRITE(strOtherAccount);
641 READWRITE(strComment);
645 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);