1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_WALLET_H
6 #define BITCOIN_WALLET_H
16 class CWallet : public CCryptoKeyStore
19 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
20 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
22 CWalletDB *pwalletdbEncryption;
23 CCriticalSection cs_pwalletdbEncryption;
27 std::string strWalletFile;
29 std::set<int64> setKeyPool;
30 CCriticalSection cs_setKeyPool;
32 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
33 MasterKeyMap mapMasterKeys;
34 unsigned int nMasterKeyMaxID;
40 pwalletdbEncryption = NULL;
42 CWallet(std::string strWalletFileIn)
44 strWalletFile = strWalletFileIn;
47 pwalletdbEncryption = NULL;
50 mutable CCriticalSection cs_mapWallet;
51 std::map<uint256, CWalletTx> mapWallet;
52 std::vector<uint256> vWalletUpdated;
54 std::map<uint256, int> mapRequestCount;
55 mutable CCriticalSection cs_mapRequestCount;
57 std::map<CBitcoinAddress, std::string> mapAddressBook;
58 mutable CCriticalSection cs_mapAddressBook;
60 std::vector<unsigned char> vchDefaultKey;
62 // keystore implementation
63 bool AddKey(const CKey& key);
64 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
65 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
66 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
68 bool Unlock(const std::string& strWalletPassphrase);
69 bool ChangeWalletPassphrase(const std::string& strOldWalletPassphrase, const std::string& strNewWalletPassphrase);
70 bool EncryptWallet(const std::string& strWalletPassphrase);
72 bool AddToWallet(const CWalletTx& wtxIn);
73 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
74 bool EraseFromWallet(uint256 hash);
75 void WalletUpdateSpent(const CTransaction& prevout);
76 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
77 void ReacceptWalletTransactions();
78 void ResendWalletTransactions();
79 int64 GetBalance() const;
80 int64 GetUnconfirmedBalance() const;
81 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
82 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
83 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
84 bool BroadcastTransaction(CWalletTx& wtxNew);
85 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
86 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
89 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
90 void KeepKey(int64 nIndex);
91 void ReturnKey(int64 nIndex);
92 std::vector<unsigned char> GetOrReuseKeyFromPool();
93 int64 GetOldestKeyPoolTime();
95 bool IsMine(const CTxIn& txin) const;
96 int64 GetDebit(const CTxIn& txin) const;
97 bool IsMine(const CTxOut& txout) const
99 return ::IsMine(*this, txout.scriptPubKey);
101 int64 GetCredit(const CTxOut& txout) const
103 if (!MoneyRange(txout.nValue))
104 throw std::runtime_error("CWallet::GetCredit() : value out of range");
105 return (IsMine(txout) ? txout.nValue : 0);
107 bool IsChange(const CTxOut& txout) const
109 CBitcoinAddress address;
110 if (ExtractAddress(txout.scriptPubKey, this, address))
111 CRITICAL_BLOCK(cs_mapAddressBook)
112 if (!mapAddressBook.count(address))
116 int64 GetChange(const CTxOut& txout) const
118 if (!MoneyRange(txout.nValue))
119 throw std::runtime_error("CWallet::GetChange() : value out of range");
120 return (IsChange(txout) ? txout.nValue : 0);
122 bool IsMine(const CTransaction& tx) const
124 BOOST_FOREACH(const CTxOut& txout, tx.vout)
129 bool IsFromMe(const CTransaction& tx) const
131 return (GetDebit(tx) > 0);
133 int64 GetDebit(const CTransaction& tx) const
136 BOOST_FOREACH(const CTxIn& txin, tx.vin)
138 nDebit += GetDebit(txin);
139 if (!MoneyRange(nDebit))
140 throw std::runtime_error("CWallet::GetDebit() : value out of range");
144 int64 GetCredit(const CTransaction& tx) const
147 BOOST_FOREACH(const CTxOut& txout, tx.vout)
149 nCredit += GetCredit(txout);
150 if (!MoneyRange(nCredit))
151 throw std::runtime_error("CWallet::GetCredit() : value out of range");
155 int64 GetChange(const CTransaction& tx) const
158 BOOST_FOREACH(const CTxOut& txout, tx.vout)
160 nChange += GetChange(txout);
161 if (!MoneyRange(nChange))
162 throw std::runtime_error("CWallet::GetChange() : value out of range");
166 void SetBestChain(const CBlockLocator& loc)
168 CWalletDB walletdb(strWalletFile);
169 walletdb.WriteBestBlock(loc);
172 int LoadWallet(bool& fFirstRunRet);
173 // bool BackupWallet(const std::string& strDest);
175 // requires cs_mapAddressBook lock
176 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
178 // requires cs_mapAddressBook lock
179 bool DelAddressBookName(const CBitcoinAddress& address);
181 void UpdatedTransaction(const uint256 &hashTx)
183 CRITICAL_BLOCK(cs_mapWallet)
184 vWalletUpdated.push_back(hashTx);
187 void PrintWallet(const CBlock& block);
189 void Inventory(const uint256 &hash)
191 CRITICAL_BLOCK(cs_mapRequestCount)
193 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
194 if (mi != mapRequestCount.end())
201 return setKeyPool.size();
204 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
206 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
215 std::vector<unsigned char> vchPubKey;
217 CReserveKey(CWallet* pwalletIn)
230 std::vector<unsigned char> GetReservedKey();
236 // A transaction with a bunch of additional info that only the owner cares
237 // about. It includes any unrecorded transactions needed to link it back
238 // to the block chain.
240 class CWalletTx : public CMerkleTx
243 const CWallet* pwallet;
245 std::vector<CMerkleTx> vtxPrev;
246 std::map<std::string, std::string> mapValue;
247 std::vector<std::pair<std::string, std::string> > vOrderForm;
248 unsigned int fTimeReceivedIsTxTime;
249 unsigned int nTimeReceived; // time received by this node
251 std::string strFromAccount;
252 std::vector<char> vfSpent;
255 mutable char fDebitCached;
256 mutable char fCreditCached;
257 mutable char fAvailableCreditCached;
258 mutable char fChangeCached;
259 mutable int64 nDebitCached;
260 mutable int64 nCreditCached;
261 mutable int64 nAvailableCreditCached;
262 mutable int64 nChangeCached;
264 // memory only UI hints
265 mutable unsigned int nTimeDisplayed;
266 mutable int nLinesDisplayed;
267 mutable char fConfirmedDisplayed;
274 CWalletTx(const CWallet* pwalletIn)
279 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
284 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
289 void Init(const CWallet* pwalletIn)
295 fTimeReceivedIsTxTime = false;
298 strFromAccount.clear();
300 fDebitCached = false;
301 fCreditCached = false;
302 fAvailableCreditCached = false;
303 fChangeCached = false;
306 nAvailableCreditCached = 0;
310 fConfirmedDisplayed = false;
315 CWalletTx* pthis = const_cast<CWalletTx*>(this);
322 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
325 BOOST_FOREACH(char f, vfSpent)
327 str += (f ? '1' : '0');
331 pthis->mapValue["spent"] = str;
334 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
337 READWRITE(vOrderForm);
338 READWRITE(fTimeReceivedIsTxTime);
339 READWRITE(nTimeReceived);
345 pthis->strFromAccount = pthis->mapValue["fromaccount"];
347 if (mapValue.count("spent"))
348 BOOST_FOREACH(char c, pthis->mapValue["spent"])
349 pthis->vfSpent.push_back(c != '0');
351 pthis->vfSpent.assign(vout.size(), fSpent);
354 pthis->mapValue.erase("fromaccount");
355 pthis->mapValue.erase("version");
356 pthis->mapValue.erase("spent");
359 // marks certain txout's as spent
360 // returns true if any update took place
361 bool UpdateSpent(const std::vector<char>& vfNewSpent)
363 bool fReturn = false;
364 for (int i=0; i < vfNewSpent.size(); i++)
366 if (i == vfSpent.size())
369 if (vfNewSpent[i] && !vfSpent[i])
373 fAvailableCreditCached = false;
381 fCreditCached = false;
382 fAvailableCreditCached = false;
383 fDebitCached = false;
384 fChangeCached = false;
387 void MarkSpent(unsigned int nOut)
389 if (nOut >= vout.size())
390 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
391 vfSpent.resize(vout.size());
394 vfSpent[nOut] = true;
395 fAvailableCreditCached = false;
399 bool IsSpent(unsigned int nOut) const
401 if (nOut >= vout.size())
402 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
403 if (nOut >= vfSpent.size())
405 return (!!vfSpent[nOut]);
408 int64 GetDebit() const
414 nDebitCached = pwallet->GetDebit(*this);
419 int64 GetCredit(bool fUseCache=true) const
421 // Must wait until coinbase is safely deep enough in the chain before valuing it
422 if (IsCoinBase() && GetBlocksToMaturity() > 0)
425 // GetBalance can assume transactions in mapWallet won't change
426 if (fUseCache && fCreditCached)
427 return nCreditCached;
428 nCreditCached = pwallet->GetCredit(*this);
429 fCreditCached = true;
430 return nCreditCached;
433 int64 GetAvailableCredit(bool fUseCache=true) const
435 // Must wait until coinbase is safely deep enough in the chain before valuing it
436 if (IsCoinBase() && GetBlocksToMaturity() > 0)
439 if (fUseCache && fAvailableCreditCached)
440 return nAvailableCreditCached;
443 for (int i = 0; i < vout.size(); i++)
447 const CTxOut &txout = vout[i];
448 nCredit += pwallet->GetCredit(txout);
449 if (!MoneyRange(nCredit))
450 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
454 nAvailableCreditCached = nCredit;
455 fAvailableCreditCached = true;
460 int64 GetChange() const
463 return nChangeCached;
464 nChangeCached = pwallet->GetChange(*this);
465 fChangeCached = true;
466 return nChangeCached;
469 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
470 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
472 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
473 int64& nSent, int64& nFee) const;
475 bool IsFromMe() const
477 return (GetDebit() > 0);
480 bool IsConfirmed() const
482 // Quick answer in most cases
485 if (GetDepthInMainChain() >= 1)
487 if (!IsFromMe()) // using wtx's cached debit
490 // If no confirmations but it's from us, we can still
491 // consider it confirmed if all dependencies are confirmed
492 std::map<uint256, const CMerkleTx*> mapPrev;
493 std::vector<const CMerkleTx*> vWorkQueue;
494 vWorkQueue.reserve(vtxPrev.size()+1);
495 vWorkQueue.push_back(this);
496 for (int i = 0; i < vWorkQueue.size(); i++)
498 const CMerkleTx* ptx = vWorkQueue[i];
502 if (ptx->GetDepthInMainChain() >= 1)
504 if (!pwallet->IsFromMe(*ptx))
508 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
509 mapPrev[tx.GetHash()] = &tx;
511 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
513 if (!mapPrev.count(txin.prevout.hash))
515 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
523 int64 GetTxTime() const;
524 int GetRequestCount() const;
526 void AddSupportingTransactions(CTxDB& txdb);
528 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
529 bool AcceptWalletTransaction();
531 void RelayWalletTransaction(CTxDB& txdb);
532 void RelayWalletTransaction();
537 // Private key that includes an expiration date in case it never gets used.
545 std::string strComment;
546 //// todo: add something to note what created it (user, getnewaddress, change)
547 //// maybe should have a map<string, string> property map
549 CWalletKey(int64 nExpires=0)
551 nTimeCreated = (nExpires ? GetTime() : 0);
552 nTimeExpires = nExpires;
557 if (!(nType & SER_GETHASH))
559 READWRITE(vchPrivKey);
560 READWRITE(nTimeCreated);
561 READWRITE(nTimeExpires);
562 READWRITE(strComment);
572 // Account information.
573 // Stored in wallet with key "acc"+string account name
578 std::vector<unsigned char> vchPubKey;
592 if (!(nType & SER_GETHASH))
594 READWRITE(vchPubKey);
601 // Internal transfers.
602 // Database key is acentry<account><counter>
604 class CAccountingEntry
607 std::string strAccount;
610 std::string strOtherAccount;
611 std::string strComment;
623 strOtherAccount.clear();
629 if (!(nType & SER_GETHASH))
631 // Note: strAccount is serialized as part of the key, not here.
632 READWRITE(nCreditDebit);
634 READWRITE(strOtherAccount);
635 READWRITE(strComment);
639 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);