1 // Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
4 #ifndef BITCOIN_WALLET_H
5 #define BITCOIN_WALLET_H
15 class CWallet : public CCryptoKeyStore
18 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
19 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
24 std::string strWalletFile;
26 std::set<int64> setKeyPool;
27 CCriticalSection cs_setKeyPool;
33 CWallet(std::string strWalletFileIn)
35 strWalletFile = strWalletFileIn;
39 mutable CCriticalSection cs_mapWallet;
40 std::map<uint256, CWalletTx> mapWallet;
41 std::vector<uint256> vWalletUpdated;
43 std::map<uint256, int> mapRequestCount;
44 mutable CCriticalSection cs_mapRequestCount;
46 std::map<std::string, std::string> mapAddressBook;
47 mutable CCriticalSection cs_mapAddressBook;
49 std::vector<unsigned char> vchDefaultKey;
51 // keystore implementation
52 bool AddKey(const CKey& key);
53 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
55 bool AddToWallet(const CWalletTx& wtxIn);
56 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
57 bool EraseFromWallet(uint256 hash);
58 void WalletUpdateSpent(const CTransaction& prevout);
59 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
60 void ReacceptWalletTransactions();
61 void ResendWalletTransactions();
62 int64 GetBalance() const;
63 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
64 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
65 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
66 bool BroadcastTransaction(CWalletTx& wtxNew);
67 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
68 std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
70 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
71 void KeepKey(int64 nIndex);
72 void ReturnKey(int64 nIndex);
73 std::vector<unsigned char> GetKeyFromKeyPool();
74 int64 GetOldestKeyPoolTime();
76 bool IsMine(const CTxIn& txin) const;
77 int64 GetDebit(const CTxIn& txin) const;
78 bool IsMine(const CTxOut& txout) const
80 return ::IsMine(*this, txout.scriptPubKey);
82 int64 GetCredit(const CTxOut& txout) const
84 if (!MoneyRange(txout.nValue))
85 throw std::runtime_error("CWallet::GetCredit() : value out of range");
86 return (IsMine(txout) ? txout.nValue : 0);
88 bool IsChange(const CTxOut& txout) const
90 std::vector<unsigned char> vchPubKey;
91 if (ExtractPubKey(txout.scriptPubKey, this, vchPubKey))
92 CRITICAL_BLOCK(cs_mapAddressBook)
93 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
97 int64 GetChange(const CTxOut& txout) const
99 if (!MoneyRange(txout.nValue))
100 throw std::runtime_error("CWallet::GetChange() : value out of range");
101 return (IsChange(txout) ? txout.nValue : 0);
103 bool IsMine(const CTransaction& tx) const
105 BOOST_FOREACH(const CTxOut& txout, tx.vout)
110 bool IsFromMe(const CTransaction& tx) const
112 return (GetDebit(tx) > 0);
114 int64 GetDebit(const CTransaction& tx) const
117 BOOST_FOREACH(const CTxIn& txin, tx.vin)
119 nDebit += GetDebit(txin);
120 if (!MoneyRange(nDebit))
121 throw std::runtime_error("CWallet::GetDebit() : value out of range");
125 int64 GetCredit(const CTransaction& tx) const
128 BOOST_FOREACH(const CTxOut& txout, tx.vout)
130 nCredit += GetCredit(txout);
131 if (!MoneyRange(nCredit))
132 throw std::runtime_error("CWallet::GetCredit() : value out of range");
136 int64 GetChange(const CTransaction& tx) const
139 BOOST_FOREACH(const CTxOut& txout, tx.vout)
141 nChange += GetChange(txout);
142 if (!MoneyRange(nChange))
143 throw std::runtime_error("CWallet::GetChange() : value out of range");
147 void SetBestChain(const CBlockLocator& loc)
149 CWalletDB walletdb(strWalletFile);
150 walletdb.WriteBestBlock(loc);
153 bool LoadWallet(bool& fFirstRunRet);
154 // bool BackupWallet(const std::string& strDest);
156 // requires cs_mapAddressBook lock
157 bool SetAddressBookName(const std::string& strAddress, const std::string& strName);
159 // requires cs_mapAddressBook lock
160 bool DelAddressBookName(const std::string& strAddress);
162 void UpdatedTransaction(const uint256 &hashTx)
164 CRITICAL_BLOCK(cs_mapWallet)
165 vWalletUpdated.push_back(hashTx);
168 void PrintWallet(const CBlock& block);
170 void Inventory(const uint256 &hash)
172 CRITICAL_BLOCK(cs_mapRequestCount)
174 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
175 if (mi != mapRequestCount.end())
180 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
182 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
191 std::vector<unsigned char> vchPubKey;
193 CReserveKey(CWallet* pwalletIn)
206 std::vector<unsigned char> GetReservedKey();
212 // A transaction with a bunch of additional info that only the owner cares
213 // about. It includes any unrecorded transactions needed to link it back
214 // to the block chain.
216 class CWalletTx : public CMerkleTx
219 const CWallet* pwallet;
221 std::vector<CMerkleTx> vtxPrev;
222 std::map<std::string, std::string> mapValue;
223 std::vector<std::pair<std::string, std::string> > vOrderForm;
224 unsigned int fTimeReceivedIsTxTime;
225 unsigned int nTimeReceived; // time received by this node
227 std::string strFromAccount;
228 std::vector<char> vfSpent;
231 mutable char fDebitCached;
232 mutable char fCreditCached;
233 mutable char fAvailableCreditCached;
234 mutable char fChangeCached;
235 mutable int64 nDebitCached;
236 mutable int64 nCreditCached;
237 mutable int64 nAvailableCreditCached;
238 mutable int64 nChangeCached;
240 // memory only UI hints
241 mutable unsigned int nTimeDisplayed;
242 mutable int nLinesDisplayed;
243 mutable char fConfirmedDisplayed;
250 CWalletTx(const CWallet* pwalletIn)
255 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
260 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
265 void Init(const CWallet* pwalletIn)
271 fTimeReceivedIsTxTime = false;
274 strFromAccount.clear();
276 fDebitCached = false;
277 fCreditCached = false;
278 fAvailableCreditCached = false;
279 fChangeCached = false;
282 nAvailableCreditCached = 0;
286 fConfirmedDisplayed = false;
291 CWalletTx* pthis = const_cast<CWalletTx*>(this);
298 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
301 BOOST_FOREACH(char f, vfSpent)
303 str += (f ? '1' : '0');
307 pthis->mapValue["spent"] = str;
310 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
313 READWRITE(vOrderForm);
314 READWRITE(fTimeReceivedIsTxTime);
315 READWRITE(nTimeReceived);
321 pthis->strFromAccount = pthis->mapValue["fromaccount"];
323 if (mapValue.count("spent"))
324 BOOST_FOREACH(char c, pthis->mapValue["spent"])
325 pthis->vfSpent.push_back(c != '0');
327 pthis->vfSpent.assign(vout.size(), fSpent);
330 pthis->mapValue.erase("fromaccount");
331 pthis->mapValue.erase("version");
332 pthis->mapValue.erase("spent");
335 // marks certain txout's as spent
336 // returns true if any update took place
337 bool UpdateSpent(const std::vector<char>& vfNewSpent)
339 bool fReturn = false;
340 for (int i=0; i < vfNewSpent.size(); i++)
342 if (i == vfSpent.size())
345 if (vfNewSpent[i] && !vfSpent[i])
349 fAvailableCreditCached = false;
357 fCreditCached = false;
358 fAvailableCreditCached = false;
359 fDebitCached = false;
360 fChangeCached = false;
363 void MarkSpent(unsigned int nOut)
365 if (nOut >= vout.size())
366 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
367 vfSpent.resize(vout.size());
370 vfSpent[nOut] = true;
371 fAvailableCreditCached = false;
375 bool IsSpent(unsigned int nOut) const
377 if (nOut >= vout.size())
378 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
379 if (nOut >= vfSpent.size())
381 return (!!vfSpent[nOut]);
384 int64 GetDebit() const
390 nDebitCached = pwallet->GetDebit(*this);
395 int64 GetCredit(bool fUseCache=true) const
397 // Must wait until coinbase is safely deep enough in the chain before valuing it
398 if (IsCoinBase() && GetBlocksToMaturity() > 0)
401 // GetBalance can assume transactions in mapWallet won't change
402 if (fUseCache && fCreditCached)
403 return nCreditCached;
404 nCreditCached = pwallet->GetCredit(*this);
405 fCreditCached = true;
406 return nCreditCached;
409 int64 GetAvailableCredit(bool fUseCache=true) const
411 // Must wait until coinbase is safely deep enough in the chain before valuing it
412 if (IsCoinBase() && GetBlocksToMaturity() > 0)
415 if (fUseCache && fAvailableCreditCached)
416 return nAvailableCreditCached;
419 for (int i = 0; i < vout.size(); i++)
423 const CTxOut &txout = vout[i];
424 nCredit += pwallet->GetCredit(txout);
425 if (!MoneyRange(nCredit))
426 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
430 nAvailableCreditCached = nCredit;
431 fAvailableCreditCached = true;
436 int64 GetChange() const
439 return nChangeCached;
440 nChangeCached = pwallet->GetChange(*this);
441 fChangeCached = true;
442 return nChangeCached;
445 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
446 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
448 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
449 int64& nSent, int64& nFee) const;
451 bool IsFromMe() const
453 return (GetDebit() > 0);
456 bool IsConfirmed() const
458 // Quick answer in most cases
461 if (GetDepthInMainChain() >= 1)
463 if (!IsFromMe()) // using wtx's cached debit
466 // If no confirmations but it's from us, we can still
467 // consider it confirmed if all dependencies are confirmed
468 std::map<uint256, const CMerkleTx*> mapPrev;
469 std::vector<const CMerkleTx*> vWorkQueue;
470 vWorkQueue.reserve(vtxPrev.size()+1);
471 vWorkQueue.push_back(this);
472 for (int i = 0; i < vWorkQueue.size(); i++)
474 const CMerkleTx* ptx = vWorkQueue[i];
478 if (ptx->GetDepthInMainChain() >= 1)
480 if (!pwallet->IsFromMe(*ptx))
484 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
485 mapPrev[tx.GetHash()] = &tx;
487 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
489 if (!mapPrev.count(txin.prevout.hash))
491 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
499 int64 GetTxTime() const;
500 int GetRequestCount() const;
502 void AddSupportingTransactions(CTxDB& txdb);
504 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
505 bool AcceptWalletTransaction();
507 void RelayWalletTransaction(CTxDB& txdb);
508 void RelayWalletTransaction();
513 // Private key that includes an expiration date in case it never gets used.
521 std::string strComment;
522 //// todo: add something to note what created it (user, getnewaddress, change)
523 //// maybe should have a map<string, string> property map
525 CWalletKey(int64 nExpires=0)
527 nTimeCreated = (nExpires ? GetTime() : 0);
528 nTimeExpires = nExpires;
533 if (!(nType & SER_GETHASH))
535 READWRITE(vchPrivKey);
536 READWRITE(nTimeCreated);
537 READWRITE(nTimeExpires);
538 READWRITE(strComment);
548 // Account information.
549 // Stored in wallet with key "acc"+string account name
554 std::vector<unsigned char> vchPubKey;
568 if (!(nType & SER_GETHASH))
570 READWRITE(vchPubKey);
577 // Internal transfers.
578 // Database key is acentry<account><counter>
580 class CAccountingEntry
583 std::string strAccount;
586 std::string strOtherAccount;
587 std::string strComment;
599 strOtherAccount.clear();
605 if (!(nType & SER_GETHASH))
607 // Note: strAccount is serialized as part of the key, not here.
608 READWRITE(nCreditDebit);
610 READWRITE(strOtherAccount);
611 READWRITE(strComment);
615 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);