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;
29 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
30 MasterKeyMap mapMasterKeys;
31 unsigned int nMasterKeyMaxID;
38 CWallet(std::string strWalletFileIn)
40 strWalletFile = strWalletFileIn;
45 mutable CCriticalSection cs_mapWallet;
46 std::map<uint256, CWalletTx> mapWallet;
47 std::vector<uint256> vWalletUpdated;
49 std::map<uint256, int> mapRequestCount;
50 mutable CCriticalSection cs_mapRequestCount;
52 std::map<std::string, std::string> mapAddressBook;
53 mutable CCriticalSection cs_mapAddressBook;
55 std::vector<unsigned char> vchDefaultKey;
57 // keystore implementation
58 bool AddKey(const CKey& key);
59 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
60 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
61 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
63 bool Unlock(const std::string& strWalletPassphrase);
64 bool ChangeWalletPassphrase(const std::string& strOldWalletPassphrase, const std::string& strNewWalletPassphrase);
65 bool EncryptWallet(const std::string& strWalletPassphrase);
67 bool AddToWallet(const CWalletTx& wtxIn);
68 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
69 bool EraseFromWallet(uint256 hash);
70 void WalletUpdateSpent(const CTransaction& prevout);
71 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
72 void ReacceptWalletTransactions();
73 void ResendWalletTransactions();
74 int64 GetBalance() const;
75 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
76 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
77 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
78 bool BroadcastTransaction(CWalletTx& wtxNew);
79 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
80 std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
83 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
84 void KeepKey(int64 nIndex);
85 void ReturnKey(int64 nIndex);
86 std::vector<unsigned char> GetOrReuseKeyFromPool();
87 int64 GetOldestKeyPoolTime();
89 bool IsMine(const CTxIn& txin) const;
90 int64 GetDebit(const CTxIn& txin) const;
91 bool IsMine(const CTxOut& txout) const
93 return ::IsMine(*this, txout.scriptPubKey);
95 int64 GetCredit(const CTxOut& txout) const
97 if (!MoneyRange(txout.nValue))
98 throw std::runtime_error("CWallet::GetCredit() : value out of range");
99 return (IsMine(txout) ? txout.nValue : 0);
101 bool IsChange(const CTxOut& txout) const
103 std::vector<unsigned char> vchPubKey;
104 if (ExtractPubKey(txout.scriptPubKey, this, vchPubKey))
105 CRITICAL_BLOCK(cs_mapAddressBook)
106 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
110 int64 GetChange(const CTxOut& txout) const
112 if (!MoneyRange(txout.nValue))
113 throw std::runtime_error("CWallet::GetChange() : value out of range");
114 return (IsChange(txout) ? txout.nValue : 0);
116 bool IsMine(const CTransaction& tx) const
118 BOOST_FOREACH(const CTxOut& txout, tx.vout)
123 bool IsFromMe(const CTransaction& tx) const
125 return (GetDebit(tx) > 0);
127 int64 GetDebit(const CTransaction& tx) const
130 BOOST_FOREACH(const CTxIn& txin, tx.vin)
132 nDebit += GetDebit(txin);
133 if (!MoneyRange(nDebit))
134 throw std::runtime_error("CWallet::GetDebit() : value out of range");
138 int64 GetCredit(const CTransaction& tx) const
141 BOOST_FOREACH(const CTxOut& txout, tx.vout)
143 nCredit += GetCredit(txout);
144 if (!MoneyRange(nCredit))
145 throw std::runtime_error("CWallet::GetCredit() : value out of range");
149 int64 GetChange(const CTransaction& tx) const
152 BOOST_FOREACH(const CTxOut& txout, tx.vout)
154 nChange += GetChange(txout);
155 if (!MoneyRange(nChange))
156 throw std::runtime_error("CWallet::GetChange() : value out of range");
160 void SetBestChain(const CBlockLocator& loc)
162 CWalletDB walletdb(strWalletFile);
163 walletdb.WriteBestBlock(loc);
166 bool LoadWallet(bool& fFirstRunRet);
167 // bool BackupWallet(const std::string& strDest);
169 // requires cs_mapAddressBook lock
170 bool SetAddressBookName(const std::string& strAddress, const std::string& strName);
172 // requires cs_mapAddressBook lock
173 bool DelAddressBookName(const std::string& strAddress);
175 void UpdatedTransaction(const uint256 &hashTx)
177 CRITICAL_BLOCK(cs_mapWallet)
178 vWalletUpdated.push_back(hashTx);
181 void PrintWallet(const CBlock& block);
183 void Inventory(const uint256 &hash)
185 CRITICAL_BLOCK(cs_mapRequestCount)
187 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
188 if (mi != mapRequestCount.end())
195 return setKeyPool.size();
198 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
200 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
209 std::vector<unsigned char> vchPubKey;
211 CReserveKey(CWallet* pwalletIn)
224 std::vector<unsigned char> GetReservedKey();
230 // A transaction with a bunch of additional info that only the owner cares
231 // about. It includes any unrecorded transactions needed to link it back
232 // to the block chain.
234 class CWalletTx : public CMerkleTx
237 const CWallet* pwallet;
239 std::vector<CMerkleTx> vtxPrev;
240 std::map<std::string, std::string> mapValue;
241 std::vector<std::pair<std::string, std::string> > vOrderForm;
242 unsigned int fTimeReceivedIsTxTime;
243 unsigned int nTimeReceived; // time received by this node
245 std::string strFromAccount;
246 std::vector<char> vfSpent;
249 mutable char fDebitCached;
250 mutable char fCreditCached;
251 mutable char fAvailableCreditCached;
252 mutable char fChangeCached;
253 mutable int64 nDebitCached;
254 mutable int64 nCreditCached;
255 mutable int64 nAvailableCreditCached;
256 mutable int64 nChangeCached;
258 // memory only UI hints
259 mutable unsigned int nTimeDisplayed;
260 mutable int nLinesDisplayed;
261 mutable char fConfirmedDisplayed;
268 CWalletTx(const CWallet* pwalletIn)
273 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
278 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
283 void Init(const CWallet* pwalletIn)
289 fTimeReceivedIsTxTime = false;
292 strFromAccount.clear();
294 fDebitCached = false;
295 fCreditCached = false;
296 fAvailableCreditCached = false;
297 fChangeCached = false;
300 nAvailableCreditCached = 0;
304 fConfirmedDisplayed = false;
309 CWalletTx* pthis = const_cast<CWalletTx*>(this);
316 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
319 BOOST_FOREACH(char f, vfSpent)
321 str += (f ? '1' : '0');
325 pthis->mapValue["spent"] = str;
328 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
331 READWRITE(vOrderForm);
332 READWRITE(fTimeReceivedIsTxTime);
333 READWRITE(nTimeReceived);
339 pthis->strFromAccount = pthis->mapValue["fromaccount"];
341 if (mapValue.count("spent"))
342 BOOST_FOREACH(char c, pthis->mapValue["spent"])
343 pthis->vfSpent.push_back(c != '0');
345 pthis->vfSpent.assign(vout.size(), fSpent);
348 pthis->mapValue.erase("fromaccount");
349 pthis->mapValue.erase("version");
350 pthis->mapValue.erase("spent");
353 // marks certain txout's as spent
354 // returns true if any update took place
355 bool UpdateSpent(const std::vector<char>& vfNewSpent)
357 bool fReturn = false;
358 for (int i=0; i < vfNewSpent.size(); i++)
360 if (i == vfSpent.size())
363 if (vfNewSpent[i] && !vfSpent[i])
367 fAvailableCreditCached = false;
375 fCreditCached = false;
376 fAvailableCreditCached = false;
377 fDebitCached = false;
378 fChangeCached = false;
381 void MarkSpent(unsigned int nOut)
383 if (nOut >= vout.size())
384 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
385 vfSpent.resize(vout.size());
388 vfSpent[nOut] = true;
389 fAvailableCreditCached = false;
393 bool IsSpent(unsigned int nOut) const
395 if (nOut >= vout.size())
396 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
397 if (nOut >= vfSpent.size())
399 return (!!vfSpent[nOut]);
402 int64 GetDebit() const
408 nDebitCached = pwallet->GetDebit(*this);
413 int64 GetCredit(bool fUseCache=true) const
415 // Must wait until coinbase is safely deep enough in the chain before valuing it
416 if (IsCoinBase() && GetBlocksToMaturity() > 0)
419 // GetBalance can assume transactions in mapWallet won't change
420 if (fUseCache && fCreditCached)
421 return nCreditCached;
422 nCreditCached = pwallet->GetCredit(*this);
423 fCreditCached = true;
424 return nCreditCached;
427 int64 GetAvailableCredit(bool fUseCache=true) const
429 // Must wait until coinbase is safely deep enough in the chain before valuing it
430 if (IsCoinBase() && GetBlocksToMaturity() > 0)
433 if (fUseCache && fAvailableCreditCached)
434 return nAvailableCreditCached;
437 for (int i = 0; i < vout.size(); i++)
441 const CTxOut &txout = vout[i];
442 nCredit += pwallet->GetCredit(txout);
443 if (!MoneyRange(nCredit))
444 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
448 nAvailableCreditCached = nCredit;
449 fAvailableCreditCached = true;
454 int64 GetChange() const
457 return nChangeCached;
458 nChangeCached = pwallet->GetChange(*this);
459 fChangeCached = true;
460 return nChangeCached;
463 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
464 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
466 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
467 int64& nSent, int64& nFee) const;
469 bool IsFromMe() const
471 return (GetDebit() > 0);
474 bool IsConfirmed() const
476 // Quick answer in most cases
479 if (GetDepthInMainChain() >= 1)
481 if (!IsFromMe()) // using wtx's cached debit
484 // If no confirmations but it's from us, we can still
485 // consider it confirmed if all dependencies are confirmed
486 std::map<uint256, const CMerkleTx*> mapPrev;
487 std::vector<const CMerkleTx*> vWorkQueue;
488 vWorkQueue.reserve(vtxPrev.size()+1);
489 vWorkQueue.push_back(this);
490 for (int i = 0; i < vWorkQueue.size(); i++)
492 const CMerkleTx* ptx = vWorkQueue[i];
496 if (ptx->GetDepthInMainChain() >= 1)
498 if (!pwallet->IsFromMe(*ptx))
502 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
503 mapPrev[tx.GetHash()] = &tx;
505 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
507 if (!mapPrev.count(txin.prevout.hash))
509 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
517 int64 GetTxTime() const;
518 int GetRequestCount() const;
520 void AddSupportingTransactions(CTxDB& txdb);
522 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
523 bool AcceptWalletTransaction();
525 void RelayWalletTransaction(CTxDB& txdb);
526 void RelayWalletTransaction();
531 // Private key that includes an expiration date in case it never gets used.
539 std::string strComment;
540 //// todo: add something to note what created it (user, getnewaddress, change)
541 //// maybe should have a map<string, string> property map
543 CWalletKey(int64 nExpires=0)
545 nTimeCreated = (nExpires ? GetTime() : 0);
546 nTimeExpires = nExpires;
551 if (!(nType & SER_GETHASH))
553 READWRITE(vchPrivKey);
554 READWRITE(nTimeCreated);
555 READWRITE(nTimeExpires);
556 READWRITE(strComment);
566 // Account information.
567 // Stored in wallet with key "acc"+string account name
572 std::vector<unsigned char> vchPubKey;
586 if (!(nType & SER_GETHASH))
588 READWRITE(vchPubKey);
595 // Internal transfers.
596 // Database key is acentry<account><counter>
598 class CAccountingEntry
601 std::string strAccount;
604 std::string strOtherAccount;
605 std::string strComment;
617 strOtherAccount.clear();
623 if (!(nType & SER_GETHASH))
625 // Note: strAccount is serialized as part of the key, not here.
626 READWRITE(nCreditDebit);
628 READWRITE(strOtherAccount);
629 READWRITE(strComment);
633 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);