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 // A CWallet is an extension of a keystore, which also maintains a set of
17 // transactions and balances, and provides the ability to create new
19 class CWallet : public CCryptoKeyStore
22 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
23 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
25 CWalletDB *pwalletdbEncryption;
28 mutable CCriticalSection cs_wallet;
31 std::string strWalletFile;
33 std::set<int64> setKeyPool;
35 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
36 MasterKeyMap mapMasterKeys;
37 unsigned int nMasterKeyMaxID;
43 pwalletdbEncryption = NULL;
45 CWallet(std::string strWalletFileIn)
47 strWalletFile = strWalletFileIn;
50 pwalletdbEncryption = NULL;
53 std::map<uint256, CWalletTx> mapWallet;
54 std::vector<uint256> vWalletUpdated;
56 std::map<uint256, int> mapRequestCount;
58 std::map<CBitcoinAddress, std::string> mapAddressBook;
60 std::vector<unsigned char> vchDefaultKey;
62 // keystore implementation
63 // Adds a key to the store, and saves it to disk.
64 bool AddKey(const CKey& key);
65 // Adds a key to the store, without saving it to disk (used by LoadWallet)
66 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
68 // Adds an encrypted key to the store, and saves it to disk.
69 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
70 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
71 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
73 bool Unlock(const SecureString& strWalletPassphrase);
74 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
75 bool EncryptWallet(const SecureString& strWalletPassphrase);
77 bool AddToWallet(const CWalletTx& wtxIn);
78 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
79 bool EraseFromWallet(uint256 hash);
80 void WalletUpdateSpent(const CTransaction& prevout);
81 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
82 void ReacceptWalletTransactions();
83 void ResendWalletTransactions();
84 int64 GetBalance() const;
85 int64 GetUnconfirmedBalance() const;
86 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
87 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
88 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
89 bool BroadcastTransaction(CWalletTx& wtxNew);
90 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
91 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
95 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
96 void KeepKey(int64 nIndex);
97 void ReturnKey(int64 nIndex);
98 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
99 int64 GetOldestKeyPoolTime();
101 bool IsMine(const CTxIn& txin) const;
102 int64 GetDebit(const CTxIn& txin) const;
103 bool IsMine(const CTxOut& txout) const
105 return ::IsMine(*this, txout.scriptPubKey);
107 int64 GetCredit(const CTxOut& txout) const
109 if (!MoneyRange(txout.nValue))
110 throw std::runtime_error("CWallet::GetCredit() : value out of range");
111 return (IsMine(txout) ? txout.nValue : 0);
113 bool IsChange(const CTxOut& txout) const
115 CBitcoinAddress address;
116 if (ExtractAddress(txout.scriptPubKey, this, address))
117 CRITICAL_BLOCK(cs_wallet)
118 if (!mapAddressBook.count(address))
122 int64 GetChange(const CTxOut& txout) const
124 if (!MoneyRange(txout.nValue))
125 throw std::runtime_error("CWallet::GetChange() : value out of range");
126 return (IsChange(txout) ? txout.nValue : 0);
128 bool IsMine(const CTransaction& tx) const
130 BOOST_FOREACH(const CTxOut& txout, tx.vout)
135 bool IsFromMe(const CTransaction& tx) const
137 return (GetDebit(tx) > 0);
139 int64 GetDebit(const CTransaction& tx) const
142 BOOST_FOREACH(const CTxIn& txin, tx.vin)
144 nDebit += GetDebit(txin);
145 if (!MoneyRange(nDebit))
146 throw std::runtime_error("CWallet::GetDebit() : value out of range");
150 int64 GetCredit(const CTransaction& tx) const
153 BOOST_FOREACH(const CTxOut& txout, tx.vout)
155 nCredit += GetCredit(txout);
156 if (!MoneyRange(nCredit))
157 throw std::runtime_error("CWallet::GetCredit() : value out of range");
161 int64 GetChange(const CTransaction& tx) const
164 BOOST_FOREACH(const CTxOut& txout, tx.vout)
166 nChange += GetChange(txout);
167 if (!MoneyRange(nChange))
168 throw std::runtime_error("CWallet::GetChange() : value out of range");
172 void SetBestChain(const CBlockLocator& loc)
174 CWalletDB walletdb(strWalletFile);
175 walletdb.WriteBestBlock(loc);
178 int LoadWallet(bool& fFirstRunRet);
179 // bool BackupWallet(const std::string& strDest);
181 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
183 bool DelAddressBookName(const CBitcoinAddress& address);
185 void UpdatedTransaction(const uint256 &hashTx)
187 CRITICAL_BLOCK(cs_wallet)
188 vWalletUpdated.push_back(hashTx);
191 void PrintWallet(const CBlock& block);
193 void Inventory(const uint256 &hash)
195 CRITICAL_BLOCK(cs_wallet)
197 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
198 if (mi != mapRequestCount.end())
205 return setKeyPool.size();
208 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
210 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
219 std::vector<unsigned char> vchPubKey;
221 CReserveKey(CWallet* pwalletIn)
234 std::vector<unsigned char> GetReservedKey();
240 // A transaction with a bunch of additional info that only the owner cares
241 // about. It includes any unrecorded transactions needed to link it back
242 // to the block chain.
244 class CWalletTx : public CMerkleTx
247 const CWallet* pwallet;
249 std::vector<CMerkleTx> vtxPrev;
250 std::map<std::string, std::string> mapValue;
251 std::vector<std::pair<std::string, std::string> > vOrderForm;
252 unsigned int fTimeReceivedIsTxTime;
253 unsigned int nTimeReceived; // time received by this node
255 std::string strFromAccount;
256 std::vector<char> vfSpent; // which outputs are already spent
259 mutable char fDebitCached;
260 mutable char fCreditCached;
261 mutable char fAvailableCreditCached;
262 mutable char fChangeCached;
263 mutable int64 nDebitCached;
264 mutable int64 nCreditCached;
265 mutable int64 nAvailableCreditCached;
266 mutable int64 nChangeCached;
268 // memory only UI hints
269 mutable unsigned int nTimeDisplayed;
270 mutable int nLinesDisplayed;
271 mutable char fConfirmedDisplayed;
278 CWalletTx(const CWallet* pwalletIn)
283 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
288 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
293 void Init(const CWallet* pwalletIn)
299 fTimeReceivedIsTxTime = false;
302 strFromAccount.clear();
304 fDebitCached = false;
305 fCreditCached = false;
306 fAvailableCreditCached = false;
307 fChangeCached = false;
310 nAvailableCreditCached = 0;
314 fConfirmedDisplayed = false;
319 CWalletTx* pthis = const_cast<CWalletTx*>(this);
326 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
329 BOOST_FOREACH(char f, vfSpent)
331 str += (f ? '1' : '0');
335 pthis->mapValue["spent"] = str;
338 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
341 READWRITE(vOrderForm);
342 READWRITE(fTimeReceivedIsTxTime);
343 READWRITE(nTimeReceived);
349 pthis->strFromAccount = pthis->mapValue["fromaccount"];
351 if (mapValue.count("spent"))
352 BOOST_FOREACH(char c, pthis->mapValue["spent"])
353 pthis->vfSpent.push_back(c != '0');
355 pthis->vfSpent.assign(vout.size(), fSpent);
358 pthis->mapValue.erase("fromaccount");
359 pthis->mapValue.erase("version");
360 pthis->mapValue.erase("spent");
363 // marks certain txout's as spent
364 // returns true if any update took place
365 bool UpdateSpent(const std::vector<char>& vfNewSpent)
367 bool fReturn = false;
368 for (int i=0; i < vfNewSpent.size(); i++)
370 if (i == vfSpent.size())
373 if (vfNewSpent[i] && !vfSpent[i])
377 fAvailableCreditCached = false;
383 // make sure balances are recalculated
386 fCreditCached = false;
387 fAvailableCreditCached = false;
388 fDebitCached = false;
389 fChangeCached = false;
392 void MarkSpent(unsigned int nOut)
394 if (nOut >= vout.size())
395 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
396 vfSpent.resize(vout.size());
399 vfSpent[nOut] = true;
400 fAvailableCreditCached = false;
404 bool IsSpent(unsigned int nOut) const
406 if (nOut >= vout.size())
407 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
408 if (nOut >= vfSpent.size())
410 return (!!vfSpent[nOut]);
413 int64 GetDebit() const
419 nDebitCached = pwallet->GetDebit(*this);
424 int64 GetCredit(bool fUseCache=true) const
426 // Must wait until coinbase is safely deep enough in the chain before valuing it
427 if (IsCoinBase() && GetBlocksToMaturity() > 0)
430 // GetBalance can assume transactions in mapWallet won't change
431 if (fUseCache && fCreditCached)
432 return nCreditCached;
433 nCreditCached = pwallet->GetCredit(*this);
434 fCreditCached = true;
435 return nCreditCached;
438 int64 GetAvailableCredit(bool fUseCache=true) const
440 // Must wait until coinbase is safely deep enough in the chain before valuing it
441 if (IsCoinBase() && GetBlocksToMaturity() > 0)
444 if (fUseCache && fAvailableCreditCached)
445 return nAvailableCreditCached;
448 for (int i = 0; i < vout.size(); i++)
452 const CTxOut &txout = vout[i];
453 nCredit += pwallet->GetCredit(txout);
454 if (!MoneyRange(nCredit))
455 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
459 nAvailableCreditCached = nCredit;
460 fAvailableCreditCached = true;
465 int64 GetChange() const
468 return nChangeCached;
469 nChangeCached = pwallet->GetChange(*this);
470 fChangeCached = true;
471 return nChangeCached;
474 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
475 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
477 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
478 int64& nSent, int64& nFee) const;
480 bool IsFromMe() const
482 return (GetDebit() > 0);
485 bool IsConfirmed() const
487 // Quick answer in most cases
490 if (GetDepthInMainChain() >= 1)
492 if (!IsFromMe()) // using wtx's cached debit
495 // If no confirmations but it's from us, we can still
496 // consider it confirmed if all dependencies are confirmed
497 std::map<uint256, const CMerkleTx*> mapPrev;
498 std::vector<const CMerkleTx*> vWorkQueue;
499 vWorkQueue.reserve(vtxPrev.size()+1);
500 vWorkQueue.push_back(this);
501 for (int i = 0; i < vWorkQueue.size(); i++)
503 const CMerkleTx* ptx = vWorkQueue[i];
507 if (ptx->GetDepthInMainChain() >= 1)
509 if (!pwallet->IsFromMe(*ptx))
513 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
514 mapPrev[tx.GetHash()] = &tx;
516 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
518 if (!mapPrev.count(txin.prevout.hash))
520 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
528 int64 GetTxTime() const;
529 int GetRequestCount() const;
531 void AddSupportingTransactions(CTxDB& txdb);
533 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
534 bool AcceptWalletTransaction();
536 void RelayWalletTransaction(CTxDB& txdb);
537 void RelayWalletTransaction();
542 // Private key that includes an expiration date in case it never gets used.
550 std::string strComment;
551 //// todo: add something to note what created it (user, getnewaddress, change)
552 //// maybe should have a map<string, string> property map
554 CWalletKey(int64 nExpires=0)
556 nTimeCreated = (nExpires ? GetTime() : 0);
557 nTimeExpires = nExpires;
562 if (!(nType & SER_GETHASH))
564 READWRITE(vchPrivKey);
565 READWRITE(nTimeCreated);
566 READWRITE(nTimeExpires);
567 READWRITE(strComment);
577 // Account information.
578 // Stored in wallet with key "acc"+string account name
583 std::vector<unsigned char> vchPubKey;
597 if (!(nType & SER_GETHASH))
599 READWRITE(vchPubKey);
606 // Internal transfers.
607 // Database key is acentry<account><counter>
609 class CAccountingEntry
612 std::string strAccount;
615 std::string strOtherAccount;
616 std::string strComment;
628 strOtherAccount.clear();
634 if (!(nType & SER_GETHASH))
636 // Note: strAccount is serialized as part of the key, not here.
637 READWRITE(nCreditDebit);
639 READWRITE(strOtherAccount);
640 READWRITE(strComment);
644 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);