1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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
17 // A CWallet is an extension of a keystore, which also maintains a set of
18 // transactions and balances, and provides the ability to create new
20 class CWallet : public CCryptoKeyStore
23 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
24 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
26 CWalletDB *pwalletdbEncryption;
29 mutable CCriticalSection cs_wallet;
32 std::string strWalletFile;
34 std::set<int64> setKeyPool;
36 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
37 MasterKeyMap mapMasterKeys;
38 unsigned int nMasterKeyMaxID;
44 pwalletdbEncryption = NULL;
46 CWallet(std::string strWalletFileIn)
48 strWalletFile = strWalletFileIn;
51 pwalletdbEncryption = NULL;
54 std::map<uint256, CWalletTx> mapWallet;
55 std::vector<uint256> vWalletUpdated;
57 std::map<uint256, int> mapRequestCount;
59 std::map<CBitcoinAddress, std::string> mapAddressBook;
61 std::vector<unsigned char> vchDefaultKey;
63 // keystore implementation
64 // Adds a key to the store, and saves it to disk.
65 bool AddKey(const CKey& key);
66 // Adds a key to the store, without saving it to disk (used by LoadWallet)
67 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
69 // Adds an encrypted key to the store, and saves it to disk.
70 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
71 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
72 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
73 bool AddCScript(const CScript& redeemScript);
74 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
76 bool Unlock(const SecureString& strWalletPassphrase);
77 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
78 bool EncryptWallet(const SecureString& strWalletPassphrase);
81 bool AddToWallet(const CWalletTx& wtxIn);
82 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
83 bool EraseFromWallet(uint256 hash);
84 void WalletUpdateSpent(const CTransaction& prevout);
85 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
86 int ScanForWalletTransaction(const uint256& hashTx);
87 void ReacceptWalletTransactions();
88 void ResendWalletTransactions();
89 int64 GetBalance() const;
90 int64 GetUnconfirmedBalance() const;
91 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
92 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
93 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
94 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
95 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
99 int64 AddReserveKey(const CKeyPool& keypool);
100 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
101 void KeepKey(int64 nIndex);
102 void ReturnKey(int64 nIndex);
103 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
104 int64 GetOldestKeyPoolTime();
105 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
107 bool IsMine(const CTxIn& txin) const;
108 int64 GetDebit(const CTxIn& txin) const;
109 bool IsMine(const CTxOut& txout) const
111 return ::IsMine(*this, txout.scriptPubKey);
113 int64 GetCredit(const CTxOut& txout) const
115 if (!MoneyRange(txout.nValue))
116 throw std::runtime_error("CWallet::GetCredit() : value out of range");
117 return (IsMine(txout) ? txout.nValue : 0);
119 bool IsChange(const CTxOut& txout) const;
120 int64 GetChange(const CTxOut& txout) const
122 if (!MoneyRange(txout.nValue))
123 throw std::runtime_error("CWallet::GetChange() : value out of range");
124 return (IsChange(txout) ? txout.nValue : 0);
126 bool IsMine(const CTransaction& tx) const
128 BOOST_FOREACH(const CTxOut& txout, tx.vout)
133 bool IsFromMe(const CTransaction& tx) const
135 return (GetDebit(tx) > 0);
137 int64 GetDebit(const CTransaction& tx) const
140 BOOST_FOREACH(const CTxIn& txin, tx.vin)
142 nDebit += GetDebit(txin);
143 if (!MoneyRange(nDebit))
144 throw std::runtime_error("CWallet::GetDebit() : value out of range");
148 int64 GetCredit(const CTransaction& tx) const
151 BOOST_FOREACH(const CTxOut& txout, tx.vout)
153 nCredit += GetCredit(txout);
154 if (!MoneyRange(nCredit))
155 throw std::runtime_error("CWallet::GetCredit() : value out of range");
159 int64 GetChange(const CTransaction& tx) const
162 BOOST_FOREACH(const CTxOut& txout, tx.vout)
164 nChange += GetChange(txout);
165 if (!MoneyRange(nChange))
166 throw std::runtime_error("CWallet::GetChange() : value out of range");
170 void SetBestChain(const CBlockLocator& loc)
172 CWalletDB walletdb(strWalletFile);
173 walletdb.WriteBestBlock(loc);
176 int LoadWallet(bool& fFirstRunRet);
177 // bool BackupWallet(const std::string& strDest);
179 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
181 bool DelAddressBookName(const CBitcoinAddress& address);
183 void UpdatedTransaction(const uint256 &hashTx)
185 CRITICAL_BLOCK(cs_wallet)
186 vWalletUpdated.push_back(hashTx);
189 void PrintWallet(const CBlock& block);
191 void Inventory(const uint256 &hash)
193 CRITICAL_BLOCK(cs_wallet)
195 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
196 if (mi != mapRequestCount.end())
203 return setKeyPool.size();
206 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
208 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
217 std::vector<unsigned char> vchPubKey;
219 CReserveKey(CWallet* pwalletIn)
232 std::vector<unsigned char> GetReservedKey();
238 // A transaction with a bunch of additional info that only the owner cares
239 // about. It includes any unrecorded transactions needed to link it back
240 // to the block chain.
242 class CWalletTx : public CMerkleTx
245 const CWallet* pwallet;
248 std::vector<CMerkleTx> vtxPrev;
249 std::map<std::string, std::string> mapValue;
250 std::vector<std::pair<std::string, std::string> > vOrderForm;
251 unsigned int fTimeReceivedIsTxTime;
252 unsigned int nTimeReceived; // time received by this node
254 std::string strFromAccount;
255 std::vector<char> vfSpent; // which outputs are already spent
258 mutable char fDebitCached;
259 mutable char fCreditCached;
260 mutable char fAvailableCreditCached;
261 mutable char fChangeCached;
262 mutable int64 nDebitCached;
263 mutable int64 nCreditCached;
264 mutable int64 nAvailableCreditCached;
265 mutable int64 nChangeCached;
267 // memory only UI hints
268 mutable unsigned int nTimeDisplayed;
269 mutable int nLinesDisplayed;
270 mutable char fConfirmedDisplayed;
277 CWalletTx(const CWallet* pwalletIn)
282 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
287 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
292 void Init(const CWallet* pwalletIn)
298 fTimeReceivedIsTxTime = false;
301 strFromAccount.clear();
303 fDebitCached = false;
304 fCreditCached = false;
305 fAvailableCreditCached = false;
306 fChangeCached = false;
309 nAvailableCreditCached = 0;
313 fConfirmedDisplayed = false;
318 CWalletTx* pthis = const_cast<CWalletTx*>(this);
325 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
328 BOOST_FOREACH(char f, vfSpent)
330 str += (f ? '1' : '0');
334 pthis->mapValue["spent"] = str;
337 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
340 READWRITE(vOrderForm);
341 READWRITE(fTimeReceivedIsTxTime);
342 READWRITE(nTimeReceived);
348 pthis->strFromAccount = pthis->mapValue["fromaccount"];
350 if (mapValue.count("spent"))
351 BOOST_FOREACH(char c, pthis->mapValue["spent"])
352 pthis->vfSpent.push_back(c != '0');
354 pthis->vfSpent.assign(vout.size(), fSpent);
357 pthis->mapValue.erase("fromaccount");
358 pthis->mapValue.erase("version");
359 pthis->mapValue.erase("spent");
362 // marks certain txout's as spent
363 // returns true if any update took place
364 bool UpdateSpent(const std::vector<char>& vfNewSpent)
366 bool fReturn = false;
367 for (int i=0; i < vfNewSpent.size(); i++)
369 if (i == vfSpent.size())
372 if (vfNewSpent[i] && !vfSpent[i])
376 fAvailableCreditCached = false;
382 // make sure balances are recalculated
385 fCreditCached = false;
386 fAvailableCreditCached = false;
387 fDebitCached = false;
388 fChangeCached = false;
391 void BindWallet(CWallet *pwalletIn)
397 void MarkSpent(unsigned int nOut)
399 if (nOut >= vout.size())
400 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
401 vfSpent.resize(vout.size());
404 vfSpent[nOut] = true;
405 fAvailableCreditCached = false;
409 bool IsSpent(unsigned int nOut) const
411 if (nOut >= vout.size())
412 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
413 if (nOut >= vfSpent.size())
415 return (!!vfSpent[nOut]);
418 int64 GetDebit() const
424 nDebitCached = pwallet->GetDebit(*this);
429 int64 GetCredit(bool fUseCache=true) const
431 // Must wait until coinbase is safely deep enough in the chain before valuing it
432 if (IsCoinBase() && GetBlocksToMaturity() > 0)
435 // GetBalance can assume transactions in mapWallet won't change
436 if (fUseCache && fCreditCached)
437 return nCreditCached;
438 nCreditCached = pwallet->GetCredit(*this);
439 fCreditCached = true;
440 return nCreditCached;
443 int64 GetAvailableCredit(bool fUseCache=true) const
445 // Must wait until coinbase is safely deep enough in the chain before valuing it
446 if (IsCoinBase() && GetBlocksToMaturity() > 0)
449 if (fUseCache && fAvailableCreditCached)
450 return nAvailableCreditCached;
453 for (int i = 0; i < vout.size(); i++)
457 const CTxOut &txout = vout[i];
458 nCredit += pwallet->GetCredit(txout);
459 if (!MoneyRange(nCredit))
460 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
464 nAvailableCreditCached = nCredit;
465 fAvailableCreditCached = true;
470 int64 GetChange() const
473 return nChangeCached;
474 nChangeCached = pwallet->GetChange(*this);
475 fChangeCached = true;
476 return nChangeCached;
479 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
480 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
482 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
483 int64& nSent, int64& nFee) const;
485 bool IsFromMe() const
487 return (GetDebit() > 0);
490 bool IsConfirmed() const
492 // Quick answer in most cases
495 if (GetDepthInMainChain() >= 1)
497 if (!IsFromMe()) // using wtx's cached debit
500 // If no confirmations but it's from us, we can still
501 // consider it confirmed if all dependencies are confirmed
502 std::map<uint256, const CMerkleTx*> mapPrev;
503 std::vector<const CMerkleTx*> vWorkQueue;
504 vWorkQueue.reserve(vtxPrev.size()+1);
505 vWorkQueue.push_back(this);
506 for (int i = 0; i < vWorkQueue.size(); i++)
508 const CMerkleTx* ptx = vWorkQueue[i];
512 if (ptx->GetDepthInMainChain() >= 1)
514 if (!pwallet->IsFromMe(*ptx))
518 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
519 mapPrev[tx.GetHash()] = &tx;
521 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
523 if (!mapPrev.count(txin.prevout.hash))
525 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
533 int64 GetTxTime() const;
534 int GetRequestCount() const;
536 void AddSupportingTransactions(CTxDB& txdb);
538 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
539 bool AcceptWalletTransaction();
541 void RelayWalletTransaction(CTxDB& txdb);
542 void RelayWalletTransaction();
547 // Private key that includes an expiration date in case it never gets used.
555 std::string strComment;
556 //// todo: add something to note what created it (user, getnewaddress, change)
557 //// maybe should have a map<string, string> property map
559 CWalletKey(int64 nExpires=0)
561 nTimeCreated = (nExpires ? GetTime() : 0);
562 nTimeExpires = nExpires;
567 if (!(nType & SER_GETHASH))
569 READWRITE(vchPrivKey);
570 READWRITE(nTimeCreated);
571 READWRITE(nTimeExpires);
572 READWRITE(strComment);
582 // Account information.
583 // Stored in wallet with key "acc"+string account name
588 std::vector<unsigned char> vchPubKey;
602 if (!(nType & SER_GETHASH))
604 READWRITE(vchPubKey);
611 // Internal transfers.
612 // Database key is acentry<account><counter>
614 class CAccountingEntry
617 std::string strAccount;
620 std::string strOtherAccount;
621 std::string strComment;
633 strOtherAccount.clear();
639 if (!(nType & SER_GETHASH))
641 // Note: strAccount is serialized as part of the key, not here.
642 READWRITE(nCreditDebit);
644 READWRITE(strOtherAccount);
645 READWRITE(strComment);
649 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);