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;
52 bool AddKey(const CKey& key);
53 bool AddToWallet(const CWalletTx& wtxIn);
54 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
55 bool EraseFromWallet(uint256 hash);
56 void WalletUpdateSpent(const CTransaction& prevout);
57 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
58 void ReacceptWalletTransactions();
59 void ResendWalletTransactions();
60 int64 GetBalance() const;
61 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
62 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
63 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
64 bool BroadcastTransaction(CWalletTx& wtxNew);
65 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
66 std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
68 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
69 void KeepKey(int64 nIndex);
70 void ReturnKey(int64 nIndex);
71 std::vector<unsigned char> GetKeyFromKeyPool();
72 int64 GetOldestKeyPoolTime();
74 bool IsMine(const CTxIn& txin) const;
75 int64 GetDebit(const CTxIn& txin) const;
76 bool IsMine(const CTxOut& txout) const
78 return ::IsMine(*this, txout.scriptPubKey);
80 int64 GetCredit(const CTxOut& txout) const
82 if (!MoneyRange(txout.nValue))
83 throw std::runtime_error("CWallet::GetCredit() : value out of range");
84 return (IsMine(txout) ? txout.nValue : 0);
86 bool IsChange(const CTxOut& txout) const
88 std::vector<unsigned char> vchPubKey;
89 if (ExtractPubKey(txout.scriptPubKey, this, vchPubKey))
90 CRITICAL_BLOCK(cs_mapAddressBook)
91 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
95 int64 GetChange(const CTxOut& txout) const
97 if (!MoneyRange(txout.nValue))
98 throw std::runtime_error("CWallet::GetChange() : value out of range");
99 return (IsChange(txout) ? txout.nValue : 0);
101 bool IsMine(const CTransaction& tx) const
103 BOOST_FOREACH(const CTxOut& txout, tx.vout)
108 bool IsFromMe(const CTransaction& tx) const
110 return (GetDebit(tx) > 0);
112 int64 GetDebit(const CTransaction& tx) const
115 BOOST_FOREACH(const CTxIn& txin, tx.vin)
117 nDebit += GetDebit(txin);
118 if (!MoneyRange(nDebit))
119 throw std::runtime_error("CWallet::GetDebit() : value out of range");
123 int64 GetCredit(const CTransaction& tx) const
126 BOOST_FOREACH(const CTxOut& txout, tx.vout)
128 nCredit += GetCredit(txout);
129 if (!MoneyRange(nCredit))
130 throw std::runtime_error("CWallet::GetCredit() : value out of range");
134 int64 GetChange(const CTransaction& tx) const
137 BOOST_FOREACH(const CTxOut& txout, tx.vout)
139 nChange += GetChange(txout);
140 if (!MoneyRange(nChange))
141 throw std::runtime_error("CWallet::GetChange() : value out of range");
145 void SetBestChain(const CBlockLocator& loc)
147 CWalletDB walletdb(strWalletFile);
148 walletdb.WriteBestBlock(loc);
151 bool LoadWallet(bool& fFirstRunRet);
152 // bool BackupWallet(const std::string& strDest);
154 bool SetAddressBookName(const std::string& strAddress, const std::string& strName)
158 return CWalletDB(strWalletFile).WriteName(strAddress, strName);
161 void UpdatedTransaction(const uint256 &hashTx)
163 CRITICAL_BLOCK(cs_mapWallet)
164 vWalletUpdated.push_back(hashTx);
167 void PrintWallet(const CBlock& block);
169 void Inventory(const uint256 &hash)
171 CRITICAL_BLOCK(cs_mapRequestCount)
173 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
174 if (mi != mapRequestCount.end())
179 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
189 std::vector<unsigned char> vchPubKey;
191 CReserveKey(CWallet* pwalletIn)
204 std::vector<unsigned char> GetReservedKey();
210 // A transaction with a bunch of additional info that only the owner cares
211 // about. It includes any unrecorded transactions needed to link it back
212 // to the block chain.
214 class CWalletTx : public CMerkleTx
217 const CWallet* pwallet;
219 std::vector<CMerkleTx> vtxPrev;
220 std::map<std::string, std::string> mapValue;
221 std::vector<std::pair<std::string, std::string> > vOrderForm;
222 unsigned int fTimeReceivedIsTxTime;
223 unsigned int nTimeReceived; // time received by this node
225 std::string strFromAccount;
226 std::vector<char> vfSpent;
229 mutable char fDebitCached;
230 mutable char fCreditCached;
231 mutable char fAvailableCreditCached;
232 mutable char fChangeCached;
233 mutable int64 nDebitCached;
234 mutable int64 nCreditCached;
235 mutable int64 nAvailableCreditCached;
236 mutable int64 nChangeCached;
238 // memory only UI hints
239 mutable unsigned int nTimeDisplayed;
240 mutable int nLinesDisplayed;
241 mutable char fConfirmedDisplayed;
248 CWalletTx(const CWallet* pwalletIn)
253 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
258 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
263 void Init(const CWallet* pwalletIn)
269 fTimeReceivedIsTxTime = false;
272 strFromAccount.clear();
274 fDebitCached = false;
275 fCreditCached = false;
276 fAvailableCreditCached = false;
277 fChangeCached = false;
280 nAvailableCreditCached = 0;
284 fConfirmedDisplayed = false;
289 CWalletTx* pthis = const_cast<CWalletTx*>(this);
296 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
299 BOOST_FOREACH(char f, vfSpent)
301 str += (f ? '1' : '0');
305 pthis->mapValue["spent"] = str;
308 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
311 READWRITE(vOrderForm);
312 READWRITE(fTimeReceivedIsTxTime);
313 READWRITE(nTimeReceived);
319 pthis->strFromAccount = pthis->mapValue["fromaccount"];
321 if (mapValue.count("spent"))
322 BOOST_FOREACH(char c, pthis->mapValue["spent"])
323 pthis->vfSpent.push_back(c != '0');
325 pthis->vfSpent.assign(vout.size(), fSpent);
328 pthis->mapValue.erase("fromaccount");
329 pthis->mapValue.erase("version");
330 pthis->mapValue.erase("spent");
333 // marks certain txout's as spent
334 // returns true if any update took place
335 bool UpdateSpent(const std::vector<char>& vfNewSpent)
337 bool fReturn = false;
338 for (int i=0; i < vfNewSpent.size(); i++)
340 if (i == vfSpent.size())
343 if (vfNewSpent[i] && !vfSpent[i])
347 fAvailableCreditCached = false;
355 fCreditCached = false;
356 fAvailableCreditCached = false;
357 fDebitCached = false;
358 fChangeCached = false;
361 void MarkSpent(unsigned int nOut)
363 if (nOut >= vout.size())
364 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
365 vfSpent.resize(vout.size());
368 vfSpent[nOut] = true;
369 fAvailableCreditCached = false;
373 bool IsSpent(unsigned int nOut) const
375 if (nOut >= vout.size())
376 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
377 if (nOut >= vfSpent.size())
379 return (!!vfSpent[nOut]);
382 int64 GetDebit() const
388 nDebitCached = pwallet->GetDebit(*this);
393 int64 GetCredit(bool fUseCache=true) const
395 // Must wait until coinbase is safely deep enough in the chain before valuing it
396 if (IsCoinBase() && GetBlocksToMaturity() > 0)
399 // GetBalance can assume transactions in mapWallet won't change
400 if (fUseCache && fCreditCached)
401 return nCreditCached;
402 nCreditCached = pwallet->GetCredit(*this);
403 fCreditCached = true;
404 return nCreditCached;
407 int64 GetAvailableCredit(bool fUseCache=true) const
409 // Must wait until coinbase is safely deep enough in the chain before valuing it
410 if (IsCoinBase() && GetBlocksToMaturity() > 0)
413 if (fUseCache && fAvailableCreditCached)
414 return nAvailableCreditCached;
417 for (int i = 0; i < vout.size(); i++)
421 const CTxOut &txout = vout[i];
422 nCredit += pwallet->GetCredit(txout);
423 if (!MoneyRange(nCredit))
424 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
428 nAvailableCreditCached = nCredit;
429 fAvailableCreditCached = true;
434 int64 GetChange() const
437 return nChangeCached;
438 nChangeCached = pwallet->GetChange(*this);
439 fChangeCached = true;
440 return nChangeCached;
443 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
444 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
446 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
447 int64& nSent, int64& nFee) const;
449 bool IsFromMe() const
451 return (GetDebit() > 0);
454 bool IsConfirmed() const
456 // Quick answer in most cases
459 if (GetDepthInMainChain() >= 1)
461 if (!IsFromMe()) // using wtx's cached debit
464 // If no confirmations but it's from us, we can still
465 // consider it confirmed if all dependencies are confirmed
466 std::map<uint256, const CMerkleTx*> mapPrev;
467 std::vector<const CMerkleTx*> vWorkQueue;
468 vWorkQueue.reserve(vtxPrev.size()+1);
469 vWorkQueue.push_back(this);
470 for (int i = 0; i < vWorkQueue.size(); i++)
472 const CMerkleTx* ptx = vWorkQueue[i];
476 if (ptx->GetDepthInMainChain() >= 1)
478 if (!pwallet->IsFromMe(*ptx))
482 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
483 mapPrev[tx.GetHash()] = &tx;
485 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
487 if (!mapPrev.count(txin.prevout.hash))
489 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
497 int64 GetTxTime() const;
498 int GetRequestCount() const;
500 void AddSupportingTransactions(CTxDB& txdb);
502 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
503 bool AcceptWalletTransaction();
505 void RelayWalletTransaction(CTxDB& txdb);
506 void RelayWalletTransaction();
511 // Private key that includes an expiration date in case it never gets used.
519 std::string strComment;
520 //// todo: add something to note what created it (user, getnewaddress, change)
521 //// maybe should have a map<string, string> property map
523 CWalletKey(int64 nExpires=0)
525 nTimeCreated = (nExpires ? GetTime() : 0);
526 nTimeExpires = nExpires;
531 if (!(nType & SER_GETHASH))
533 READWRITE(vchPrivKey);
534 READWRITE(nTimeCreated);
535 READWRITE(nTimeExpires);
536 READWRITE(strComment);
546 // Account information.
547 // Stored in wallet with key "acc"+string account name
552 std::vector<unsigned char> vchPubKey;
566 if (!(nType & SER_GETHASH))
568 READWRITE(vchPubKey);
575 // Internal transfers.
576 // Database key is acentry<account><counter>
578 class CAccountingEntry
581 std::string strAccount;
584 std::string strOtherAccount;
585 std::string strComment;
597 strOtherAccount.clear();
603 if (!(nType & SER_GETHASH))
605 // Note: strAccount is serialized as part of the key, not here.
606 READWRITE(nCreditDebit);
608 READWRITE(strOtherAccount);
609 READWRITE(strComment);
613 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);