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);
78 bool AddToWallet(const CWalletTx& wtxIn);
79 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
80 bool EraseFromWallet(uint256 hash);
81 void WalletUpdateSpent(const CTransaction& prevout);
82 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
83 int ScanForWalletTransaction(const uint256& hashTx);
84 void ReacceptWalletTransactions();
85 void ResendWalletTransactions();
86 int64 GetBalance() const;
87 int64 GetUnconfirmedBalance() const;
88 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
89 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
90 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
91 bool BroadcastTransaction(CWalletTx& wtxNew);
92 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
93 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
97 int64 AddReserveKey(const CKeyPool& keypool);
98 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
99 void KeepKey(int64 nIndex);
100 void ReturnKey(int64 nIndex);
101 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
102 int64 GetOldestKeyPoolTime();
103 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
105 bool IsMine(const CTxIn& txin) const;
106 int64 GetDebit(const CTxIn& txin) const;
107 bool IsMine(const CTxOut& txout) const
109 return ::IsMine(*this, txout.scriptPubKey);
111 int64 GetCredit(const CTxOut& txout) const
113 if (!MoneyRange(txout.nValue))
114 throw std::runtime_error("CWallet::GetCredit() : value out of range");
115 return (IsMine(txout) ? txout.nValue : 0);
117 bool IsChange(const CTxOut& txout) const
119 CBitcoinAddress address;
120 if (ExtractAddress(txout.scriptPubKey, this, address))
121 CRITICAL_BLOCK(cs_wallet)
122 if (!mapAddressBook.count(address))
126 int64 GetChange(const CTxOut& txout) const
128 if (!MoneyRange(txout.nValue))
129 throw std::runtime_error("CWallet::GetChange() : value out of range");
130 return (IsChange(txout) ? txout.nValue : 0);
132 bool IsMine(const CTransaction& tx) const
134 BOOST_FOREACH(const CTxOut& txout, tx.vout)
139 bool IsFromMe(const CTransaction& tx) const
141 return (GetDebit(tx) > 0);
143 int64 GetDebit(const CTransaction& tx) const
146 BOOST_FOREACH(const CTxIn& txin, tx.vin)
148 nDebit += GetDebit(txin);
149 if (!MoneyRange(nDebit))
150 throw std::runtime_error("CWallet::GetDebit() : value out of range");
154 int64 GetCredit(const CTransaction& tx) const
157 BOOST_FOREACH(const CTxOut& txout, tx.vout)
159 nCredit += GetCredit(txout);
160 if (!MoneyRange(nCredit))
161 throw std::runtime_error("CWallet::GetCredit() : value out of range");
165 int64 GetChange(const CTransaction& tx) const
168 BOOST_FOREACH(const CTxOut& txout, tx.vout)
170 nChange += GetChange(txout);
171 if (!MoneyRange(nChange))
172 throw std::runtime_error("CWallet::GetChange() : value out of range");
176 void SetBestChain(const CBlockLocator& loc)
178 CWalletDB walletdb(strWalletFile);
179 walletdb.WriteBestBlock(loc);
182 int LoadWallet(bool& fFirstRunRet);
183 // bool BackupWallet(const std::string& strDest);
185 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
187 bool DelAddressBookName(const CBitcoinAddress& address);
189 void UpdatedTransaction(const uint256 &hashTx)
191 CRITICAL_BLOCK(cs_wallet)
192 vWalletUpdated.push_back(hashTx);
195 void PrintWallet(const CBlock& block);
197 void Inventory(const uint256 &hash)
199 CRITICAL_BLOCK(cs_wallet)
201 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
202 if (mi != mapRequestCount.end())
209 return setKeyPool.size();
212 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
214 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
223 std::vector<unsigned char> vchPubKey;
225 CReserveKey(CWallet* pwalletIn)
238 std::vector<unsigned char> GetReservedKey();
244 // A transaction with a bunch of additional info that only the owner cares
245 // about. It includes any unrecorded transactions needed to link it back
246 // to the block chain.
248 class CWalletTx : public CMerkleTx
251 const CWallet* pwallet;
254 std::vector<CMerkleTx> vtxPrev;
255 std::map<std::string, std::string> mapValue;
256 std::vector<std::pair<std::string, std::string> > vOrderForm;
257 unsigned int fTimeReceivedIsTxTime;
258 unsigned int nTimeReceived; // time received by this node
260 std::string strFromAccount;
261 std::vector<char> vfSpent; // which outputs are already spent
264 mutable char fDebitCached;
265 mutable char fCreditCached;
266 mutable char fAvailableCreditCached;
267 mutable char fChangeCached;
268 mutable int64 nDebitCached;
269 mutable int64 nCreditCached;
270 mutable int64 nAvailableCreditCached;
271 mutable int64 nChangeCached;
273 // memory only UI hints
274 mutable unsigned int nTimeDisplayed;
275 mutable int nLinesDisplayed;
276 mutable char fConfirmedDisplayed;
283 CWalletTx(const CWallet* pwalletIn)
288 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
293 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
298 void Init(const CWallet* pwalletIn)
304 fTimeReceivedIsTxTime = false;
307 strFromAccount.clear();
309 fDebitCached = false;
310 fCreditCached = false;
311 fAvailableCreditCached = false;
312 fChangeCached = false;
315 nAvailableCreditCached = 0;
319 fConfirmedDisplayed = false;
324 CWalletTx* pthis = const_cast<CWalletTx*>(this);
331 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
334 BOOST_FOREACH(char f, vfSpent)
336 str += (f ? '1' : '0');
340 pthis->mapValue["spent"] = str;
343 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
346 READWRITE(vOrderForm);
347 READWRITE(fTimeReceivedIsTxTime);
348 READWRITE(nTimeReceived);
354 pthis->strFromAccount = pthis->mapValue["fromaccount"];
356 if (mapValue.count("spent"))
357 BOOST_FOREACH(char c, pthis->mapValue["spent"])
358 pthis->vfSpent.push_back(c != '0');
360 pthis->vfSpent.assign(vout.size(), fSpent);
363 pthis->mapValue.erase("fromaccount");
364 pthis->mapValue.erase("version");
365 pthis->mapValue.erase("spent");
368 // marks certain txout's as spent
369 // returns true if any update took place
370 bool UpdateSpent(const std::vector<char>& vfNewSpent)
372 bool fReturn = false;
373 for (int i=0; i < vfNewSpent.size(); i++)
375 if (i == vfSpent.size())
378 if (vfNewSpent[i] && !vfSpent[i])
382 fAvailableCreditCached = false;
388 // make sure balances are recalculated
391 fCreditCached = false;
392 fAvailableCreditCached = false;
393 fDebitCached = false;
394 fChangeCached = false;
397 void BindWallet(CWallet *pwalletIn)
403 void MarkSpent(unsigned int nOut)
405 if (nOut >= vout.size())
406 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
407 vfSpent.resize(vout.size());
410 vfSpent[nOut] = true;
411 fAvailableCreditCached = false;
415 bool IsSpent(unsigned int nOut) const
417 if (nOut >= vout.size())
418 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
419 if (nOut >= vfSpent.size())
421 return (!!vfSpent[nOut]);
424 int64 GetDebit() const
430 nDebitCached = pwallet->GetDebit(*this);
435 int64 GetCredit(bool fUseCache=true) const
437 // Must wait until coinbase is safely deep enough in the chain before valuing it
438 if (IsCoinBase() && GetBlocksToMaturity() > 0)
441 // GetBalance can assume transactions in mapWallet won't change
442 if (fUseCache && fCreditCached)
443 return nCreditCached;
444 nCreditCached = pwallet->GetCredit(*this);
445 fCreditCached = true;
446 return nCreditCached;
449 int64 GetAvailableCredit(bool fUseCache=true) const
451 // Must wait until coinbase is safely deep enough in the chain before valuing it
452 if (IsCoinBase() && GetBlocksToMaturity() > 0)
455 if (fUseCache && fAvailableCreditCached)
456 return nAvailableCreditCached;
459 for (int i = 0; i < vout.size(); i++)
463 const CTxOut &txout = vout[i];
464 nCredit += pwallet->GetCredit(txout);
465 if (!MoneyRange(nCredit))
466 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
470 nAvailableCreditCached = nCredit;
471 fAvailableCreditCached = true;
476 int64 GetChange() const
479 return nChangeCached;
480 nChangeCached = pwallet->GetChange(*this);
481 fChangeCached = true;
482 return nChangeCached;
485 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
486 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
488 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
489 int64& nSent, int64& nFee) const;
491 bool IsFromMe() const
493 return (GetDebit() > 0);
496 bool IsConfirmed() const
498 // Quick answer in most cases
501 if (GetDepthInMainChain() >= 1)
503 if (!IsFromMe()) // using wtx's cached debit
506 // If no confirmations but it's from us, we can still
507 // consider it confirmed if all dependencies are confirmed
508 std::map<uint256, const CMerkleTx*> mapPrev;
509 std::vector<const CMerkleTx*> vWorkQueue;
510 vWorkQueue.reserve(vtxPrev.size()+1);
511 vWorkQueue.push_back(this);
512 for (int i = 0; i < vWorkQueue.size(); i++)
514 const CMerkleTx* ptx = vWorkQueue[i];
518 if (ptx->GetDepthInMainChain() >= 1)
520 if (!pwallet->IsFromMe(*ptx))
524 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
525 mapPrev[tx.GetHash()] = &tx;
527 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
529 if (!mapPrev.count(txin.prevout.hash))
531 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
539 int64 GetTxTime() const;
540 int GetRequestCount() const;
542 void AddSupportingTransactions(CTxDB& txdb);
544 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
545 bool AcceptWalletTransaction();
547 void RelayWalletTransaction(CTxDB& txdb);
548 void RelayWalletTransaction();
553 // Private key that includes an expiration date in case it never gets used.
561 std::string strComment;
562 //// todo: add something to note what created it (user, getnewaddress, change)
563 //// maybe should have a map<string, string> property map
565 CWalletKey(int64 nExpires=0)
567 nTimeCreated = (nExpires ? GetTime() : 0);
568 nTimeExpires = nExpires;
573 if (!(nType & SER_GETHASH))
575 READWRITE(vchPrivKey);
576 READWRITE(nTimeCreated);
577 READWRITE(nTimeExpires);
578 READWRITE(strComment);
588 // Account information.
589 // Stored in wallet with key "acc"+string account name
594 std::vector<unsigned char> vchPubKey;
608 if (!(nType & SER_GETHASH))
610 READWRITE(vchPubKey);
617 // Internal transfers.
618 // Database key is acentry<account><counter>
620 class CAccountingEntry
623 std::string strAccount;
626 std::string strOtherAccount;
627 std::string strComment;
639 strOtherAccount.clear();
645 if (!(nType & SER_GETHASH))
647 // Note: strAccount is serialized as part of the key, not here.
648 READWRITE(nCreditDebit);
650 READWRITE(strOtherAccount);
651 READWRITE(strComment);
655 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);