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 CKeyStore
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 bool AddKey(const CKey& key);
52 bool AddToWallet(const CWalletTx& wtxIn);
53 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
54 bool EraseFromWallet(uint256 hash);
55 void WalletUpdateSpent(const CTransaction& prevout);
56 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
57 void ReacceptWalletTransactions();
58 void ResendWalletTransactions();
59 int64 GetBalance() const;
60 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
61 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
62 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
63 bool BroadcastTransaction(CWalletTx& wtxNew);
64 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
65 std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
67 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
68 void KeepKey(int64 nIndex);
69 void ReturnKey(int64 nIndex);
70 std::vector<unsigned char> GetKeyFromKeyPool();
71 int64 GetOldestKeyPoolTime();
73 bool IsMine(const CTxIn& txin) const;
74 int64 GetDebit(const CTxIn& txin) const;
75 bool IsMine(const CTxOut& txout) const
77 return ::IsMine(*this, txout.scriptPubKey);
79 int64 GetCredit(const CTxOut& txout) const
81 if (!MoneyRange(txout.nValue))
82 throw std::runtime_error("CWallet::GetCredit() : value out of range");
83 return (IsMine(txout) ? txout.nValue : 0);
85 bool IsChange(const CTxOut& txout) const
87 std::vector<unsigned char> vchPubKey;
88 if (ExtractPubKey(txout.scriptPubKey, this, vchPubKey))
89 CRITICAL_BLOCK(cs_mapAddressBook)
90 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
94 int64 GetChange(const CTxOut& txout) const
96 if (!MoneyRange(txout.nValue))
97 throw std::runtime_error("CWallet::GetChange() : value out of range");
98 return (IsChange(txout) ? txout.nValue : 0);
100 bool IsMine(const CTransaction& tx) const
102 BOOST_FOREACH(const CTxOut& txout, tx.vout)
107 bool IsFromMe(const CTransaction& tx) const
109 return (GetDebit(tx) > 0);
111 int64 GetDebit(const CTransaction& tx) const
114 BOOST_FOREACH(const CTxIn& txin, tx.vin)
116 nDebit += GetDebit(txin);
117 if (!MoneyRange(nDebit))
118 throw std::runtime_error("CWallet::GetDebit() : value out of range");
122 int64 GetCredit(const CTransaction& tx) const
125 BOOST_FOREACH(const CTxOut& txout, tx.vout)
127 nCredit += GetCredit(txout);
128 if (!MoneyRange(nCredit))
129 throw std::runtime_error("CWallet::GetCredit() : value out of range");
133 int64 GetChange(const CTransaction& tx) const
136 BOOST_FOREACH(const CTxOut& txout, tx.vout)
138 nChange += GetChange(txout);
139 if (!MoneyRange(nChange))
140 throw std::runtime_error("CWallet::GetChange() : value out of range");
144 void SetBestChain(const CBlockLocator& loc)
146 CWalletDB walletdb(strWalletFile);
147 walletdb.WriteBestBlock(loc);
150 bool LoadWallet(bool& fFirstRunRet);
151 // bool BackupWallet(const std::string& strDest);
152 bool SetAddressBookName(const std::string& strAddress, const std::string& strName);
153 bool EraseAddressBookName(const std::string& strAddress);
154 std::string GetDefaultAddress();
155 bool SetDefaultAddress(const std::string& strAddress);
157 void UpdatedTransaction(const uint256 &hashTx)
159 CRITICAL_BLOCK(cs_mapWallet)
160 vWalletUpdated.push_back(hashTx);
163 void PrintWallet(const CBlock& block);
165 void Inventory(const uint256 &hash)
167 CRITICAL_BLOCK(cs_mapRequestCount)
169 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
170 if (mi != mapRequestCount.end())
175 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
185 std::vector<unsigned char> vchPubKey;
187 CReserveKey(CWallet* pwalletIn)
200 std::vector<unsigned char> GetReservedKey();
206 // A transaction with a bunch of additional info that only the owner cares
207 // about. It includes any unrecorded transactions needed to link it back
208 // to the block chain.
210 class CWalletTx : public CMerkleTx
213 const CWallet* pwallet;
215 std::vector<CMerkleTx> vtxPrev;
216 std::map<std::string, std::string> mapValue;
217 std::vector<std::pair<std::string, std::string> > vOrderForm;
218 unsigned int fTimeReceivedIsTxTime;
219 unsigned int nTimeReceived; // time received by this node
221 std::string strFromAccount;
222 std::vector<char> vfSpent;
225 mutable char fDebitCached;
226 mutable char fCreditCached;
227 mutable char fAvailableCreditCached;
228 mutable char fChangeCached;
229 mutable int64 nDebitCached;
230 mutable int64 nCreditCached;
231 mutable int64 nAvailableCreditCached;
232 mutable int64 nChangeCached;
234 // memory only UI hints
235 mutable unsigned int nTimeDisplayed;
236 mutable int nLinesDisplayed;
237 mutable char fConfirmedDisplayed;
244 CWalletTx(const CWallet* pwalletIn)
249 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
254 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
259 void Init(const CWallet* pwalletIn)
265 fTimeReceivedIsTxTime = false;
268 strFromAccount.clear();
270 fDebitCached = false;
271 fCreditCached = false;
272 fAvailableCreditCached = false;
273 fChangeCached = false;
276 nAvailableCreditCached = 0;
280 fConfirmedDisplayed = false;
285 CWalletTx* pthis = const_cast<CWalletTx*>(this);
292 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
295 BOOST_FOREACH(char f, vfSpent)
297 str += (f ? '1' : '0');
301 pthis->mapValue["spent"] = str;
304 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
307 READWRITE(vOrderForm);
308 READWRITE(fTimeReceivedIsTxTime);
309 READWRITE(nTimeReceived);
315 pthis->strFromAccount = pthis->mapValue["fromaccount"];
317 if (mapValue.count("spent"))
318 BOOST_FOREACH(char c, pthis->mapValue["spent"])
319 pthis->vfSpent.push_back(c != '0');
321 pthis->vfSpent.assign(vout.size(), fSpent);
324 pthis->mapValue.erase("fromaccount");
325 pthis->mapValue.erase("version");
326 pthis->mapValue.erase("spent");
329 // marks certain txout's as spent
330 // returns true if any update took place
331 bool UpdateSpent(const std::vector<char>& vfNewSpent)
333 bool fReturn = false;
334 for (int i=0; i < vfNewSpent.size(); i++)
336 if (i == vfSpent.size())
339 if (vfNewSpent[i] && !vfSpent[i])
343 fAvailableCreditCached = false;
351 fCreditCached = false;
352 fAvailableCreditCached = false;
353 fDebitCached = false;
354 fChangeCached = false;
357 void MarkSpent(unsigned int nOut)
359 if (nOut >= vout.size())
360 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
361 vfSpent.resize(vout.size());
364 vfSpent[nOut] = true;
365 fAvailableCreditCached = false;
369 bool IsSpent(unsigned int nOut) const
371 if (nOut >= vout.size())
372 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
373 if (nOut >= vfSpent.size())
375 return (!!vfSpent[nOut]);
378 int64 GetDebit() const
384 nDebitCached = pwallet->GetDebit(*this);
389 int64 GetCredit(bool fUseCache=true) const
391 // Must wait until coinbase is safely deep enough in the chain before valuing it
392 if (IsCoinBase() && GetBlocksToMaturity() > 0)
395 // GetBalance can assume transactions in mapWallet won't change
396 if (fUseCache && fCreditCached)
397 return nCreditCached;
398 nCreditCached = pwallet->GetCredit(*this);
399 fCreditCached = true;
400 return nCreditCached;
403 int64 GetAvailableCredit(bool fUseCache=true) const
405 // Must wait until coinbase is safely deep enough in the chain before valuing it
406 if (IsCoinBase() && GetBlocksToMaturity() > 0)
409 if (fUseCache && fAvailableCreditCached)
410 return nAvailableCreditCached;
413 for (int i = 0; i < vout.size(); i++)
417 const CTxOut &txout = vout[i];
418 nCredit += pwallet->GetCredit(txout);
419 if (!MoneyRange(nCredit))
420 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
424 nAvailableCreditCached = nCredit;
425 fAvailableCreditCached = true;
430 int64 GetChange() const
433 return nChangeCached;
434 nChangeCached = pwallet->GetChange(*this);
435 fChangeCached = true;
436 return nChangeCached;
439 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
440 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
442 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
443 int64& nSent, int64& nFee) const;
445 bool IsFromMe() const
447 return (GetDebit() > 0);
450 bool IsConfirmed() const
452 // Quick answer in most cases
455 if (GetDepthInMainChain() >= 1)
457 if (!IsFromMe()) // using wtx's cached debit
460 // If no confirmations but it's from us, we can still
461 // consider it confirmed if all dependencies are confirmed
462 std::map<uint256, const CMerkleTx*> mapPrev;
463 std::vector<const CMerkleTx*> vWorkQueue;
464 vWorkQueue.reserve(vtxPrev.size()+1);
465 vWorkQueue.push_back(this);
466 for (int i = 0; i < vWorkQueue.size(); i++)
468 const CMerkleTx* ptx = vWorkQueue[i];
472 if (ptx->GetDepthInMainChain() >= 1)
474 if (!pwallet->IsFromMe(*ptx))
478 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
479 mapPrev[tx.GetHash()] = &tx;
481 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
483 if (!mapPrev.count(txin.prevout.hash))
485 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
493 int64 GetTxTime() const;
494 int GetRequestCount() const;
496 void AddSupportingTransactions(CTxDB& txdb);
498 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
499 bool AcceptWalletTransaction();
501 void RelayWalletTransaction(CTxDB& txdb);
502 void RelayWalletTransaction();
507 // Private key that includes an expiration date in case it never gets used.
515 std::string strComment;
516 //// todo: add something to note what created it (user, getnewaddress, change)
517 //// maybe should have a map<string, string> property map
519 CWalletKey(int64 nExpires=0)
521 nTimeCreated = (nExpires ? GetTime() : 0);
522 nTimeExpires = nExpires;
527 if (!(nType & SER_GETHASH))
529 READWRITE(vchPrivKey);
530 READWRITE(nTimeCreated);
531 READWRITE(nTimeExpires);
532 READWRITE(strComment);
542 // Account information.
543 // Stored in wallet with key "acc"+string account name
548 std::vector<unsigned char> vchPubKey;
562 if (!(nType & SER_GETHASH))
564 READWRITE(vchPubKey);
571 // Internal transfers.
572 // Database key is acentry<account><counter>
574 class CAccountingEntry
577 std::string strAccount;
580 std::string strOtherAccount;
581 std::string strComment;
593 strOtherAccount.clear();
599 if (!(nType & SER_GETHASH))
601 // Note: strAccount is serialized as part of the key, not here.
602 READWRITE(nCreditDebit);
604 READWRITE(strOtherAccount);
605 READWRITE(strComment);
609 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);