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);
153 // requires cs_mapAddressBook lock
154 bool SetAddressBookName(const std::string& strAddress, const std::string& strName);
156 // requires cs_mapAddressBook lock
157 bool DelAddressBookName(const std::string& strAddress);
159 void UpdatedTransaction(const uint256 &hashTx)
161 CRITICAL_BLOCK(cs_mapWallet)
162 vWalletUpdated.push_back(hashTx);
165 void PrintWallet(const CBlock& block);
167 void Inventory(const uint256 &hash)
169 CRITICAL_BLOCK(cs_mapRequestCount)
171 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
172 if (mi != mapRequestCount.end())
177 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
179 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
188 std::vector<unsigned char> vchPubKey;
190 CReserveKey(CWallet* pwalletIn)
203 std::vector<unsigned char> GetReservedKey();
209 // A transaction with a bunch of additional info that only the owner cares
210 // about. It includes any unrecorded transactions needed to link it back
211 // to the block chain.
213 class CWalletTx : public CMerkleTx
216 const CWallet* pwallet;
218 std::vector<CMerkleTx> vtxPrev;
219 std::map<std::string, std::string> mapValue;
220 std::vector<std::pair<std::string, std::string> > vOrderForm;
221 unsigned int fTimeReceivedIsTxTime;
222 unsigned int nTimeReceived; // time received by this node
224 std::string strFromAccount;
225 std::vector<char> vfSpent;
228 mutable char fDebitCached;
229 mutable char fCreditCached;
230 mutable char fAvailableCreditCached;
231 mutable char fChangeCached;
232 mutable int64 nDebitCached;
233 mutable int64 nCreditCached;
234 mutable int64 nAvailableCreditCached;
235 mutable int64 nChangeCached;
237 // memory only UI hints
238 mutable unsigned int nTimeDisplayed;
239 mutable int nLinesDisplayed;
240 mutable char fConfirmedDisplayed;
247 CWalletTx(const CWallet* pwalletIn)
252 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
257 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
262 void Init(const CWallet* pwalletIn)
268 fTimeReceivedIsTxTime = false;
271 strFromAccount.clear();
273 fDebitCached = false;
274 fCreditCached = false;
275 fAvailableCreditCached = false;
276 fChangeCached = false;
279 nAvailableCreditCached = 0;
283 fConfirmedDisplayed = false;
288 CWalletTx* pthis = const_cast<CWalletTx*>(this);
295 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
298 BOOST_FOREACH(char f, vfSpent)
300 str += (f ? '1' : '0');
304 pthis->mapValue["spent"] = str;
307 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
310 READWRITE(vOrderForm);
311 READWRITE(fTimeReceivedIsTxTime);
312 READWRITE(nTimeReceived);
318 pthis->strFromAccount = pthis->mapValue["fromaccount"];
320 if (mapValue.count("spent"))
321 BOOST_FOREACH(char c, pthis->mapValue["spent"])
322 pthis->vfSpent.push_back(c != '0');
324 pthis->vfSpent.assign(vout.size(), fSpent);
327 pthis->mapValue.erase("fromaccount");
328 pthis->mapValue.erase("version");
329 pthis->mapValue.erase("spent");
332 // marks certain txout's as spent
333 // returns true if any update took place
334 bool UpdateSpent(const std::vector<char>& vfNewSpent)
336 bool fReturn = false;
337 for (int i=0; i < vfNewSpent.size(); i++)
339 if (i == vfSpent.size())
342 if (vfNewSpent[i] && !vfSpent[i])
346 fAvailableCreditCached = false;
354 fCreditCached = false;
355 fAvailableCreditCached = false;
356 fDebitCached = false;
357 fChangeCached = false;
360 void MarkSpent(unsigned int nOut)
362 if (nOut >= vout.size())
363 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
364 vfSpent.resize(vout.size());
367 vfSpent[nOut] = true;
368 fAvailableCreditCached = false;
372 bool IsSpent(unsigned int nOut) const
374 if (nOut >= vout.size())
375 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
376 if (nOut >= vfSpent.size())
378 return (!!vfSpent[nOut]);
381 int64 GetDebit() const
387 nDebitCached = pwallet->GetDebit(*this);
392 int64 GetCredit(bool fUseCache=true) const
394 // Must wait until coinbase is safely deep enough in the chain before valuing it
395 if (IsCoinBase() && GetBlocksToMaturity() > 0)
398 // GetBalance can assume transactions in mapWallet won't change
399 if (fUseCache && fCreditCached)
400 return nCreditCached;
401 nCreditCached = pwallet->GetCredit(*this);
402 fCreditCached = true;
403 return nCreditCached;
406 int64 GetAvailableCredit(bool fUseCache=true) const
408 // Must wait until coinbase is safely deep enough in the chain before valuing it
409 if (IsCoinBase() && GetBlocksToMaturity() > 0)
412 if (fUseCache && fAvailableCreditCached)
413 return nAvailableCreditCached;
416 for (int i = 0; i < vout.size(); i++)
420 const CTxOut &txout = vout[i];
421 nCredit += pwallet->GetCredit(txout);
422 if (!MoneyRange(nCredit))
423 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
427 nAvailableCreditCached = nCredit;
428 fAvailableCreditCached = true;
433 int64 GetChange() const
436 return nChangeCached;
437 nChangeCached = pwallet->GetChange(*this);
438 fChangeCached = true;
439 return nChangeCached;
442 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
443 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
445 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
446 int64& nSent, int64& nFee) const;
448 bool IsFromMe() const
450 return (GetDebit() > 0);
453 bool IsConfirmed() const
455 // Quick answer in most cases
458 if (GetDepthInMainChain() >= 1)
460 if (!IsFromMe()) // using wtx's cached debit
463 // If no confirmations but it's from us, we can still
464 // consider it confirmed if all dependencies are confirmed
465 std::map<uint256, const CMerkleTx*> mapPrev;
466 std::vector<const CMerkleTx*> vWorkQueue;
467 vWorkQueue.reserve(vtxPrev.size()+1);
468 vWorkQueue.push_back(this);
469 for (int i = 0; i < vWorkQueue.size(); i++)
471 const CMerkleTx* ptx = vWorkQueue[i];
475 if (ptx->GetDepthInMainChain() >= 1)
477 if (!pwallet->IsFromMe(*ptx))
481 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
482 mapPrev[tx.GetHash()] = &tx;
484 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
486 if (!mapPrev.count(txin.prevout.hash))
488 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
496 int64 GetTxTime() const;
497 int GetRequestCount() const;
499 void AddSupportingTransactions(CTxDB& txdb);
501 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
502 bool AcceptWalletTransaction();
504 void RelayWalletTransaction(CTxDB& txdb);
505 void RelayWalletTransaction();
510 // Private key that includes an expiration date in case it never gets used.
518 std::string strComment;
519 //// todo: add something to note what created it (user, getnewaddress, change)
520 //// maybe should have a map<string, string> property map
522 CWalletKey(int64 nExpires=0)
524 nTimeCreated = (nExpires ? GetTime() : 0);
525 nTimeExpires = nExpires;
530 if (!(nType & SER_GETHASH))
532 READWRITE(vchPrivKey);
533 READWRITE(nTimeCreated);
534 READWRITE(nTimeExpires);
535 READWRITE(strComment);
545 // Account information.
546 // Stored in wallet with key "acc"+string account name
551 std::vector<unsigned char> vchPubKey;
565 if (!(nType & SER_GETHASH))
567 READWRITE(vchPubKey);
574 // Internal transfers.
575 // Database key is acentry<account><counter>
577 class CAccountingEntry
580 std::string strAccount;
583 std::string strOtherAccount;
584 std::string strComment;
596 strOtherAccount.clear();
602 if (!(nType & SER_GETHASH))
604 // Note: strAccount is serialized as part of the key, not here.
605 READWRITE(nCreditDebit);
607 READWRITE(strOtherAccount);
608 READWRITE(strComment);
612 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);