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;
250 std::vector<CMerkleTx> vtxPrev;
251 std::map<std::string, std::string> mapValue;
252 std::vector<std::pair<std::string, std::string> > vOrderForm;
253 unsigned int fTimeReceivedIsTxTime;
254 unsigned int nTimeReceived; // time received by this node
256 std::string strFromAccount;
257 std::vector<char> vfSpent; // which outputs are already spent
260 mutable char fDebitCached;
261 mutable char fCreditCached;
262 mutable char fAvailableCreditCached;
263 mutable char fChangeCached;
264 mutable int64 nDebitCached;
265 mutable int64 nCreditCached;
266 mutable int64 nAvailableCreditCached;
267 mutable int64 nChangeCached;
269 // memory only UI hints
270 mutable unsigned int nTimeDisplayed;
271 mutable int nLinesDisplayed;
272 mutable char fConfirmedDisplayed;
279 CWalletTx(const CWallet* pwalletIn)
284 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
289 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
294 void Init(const CWallet* pwalletIn)
300 fTimeReceivedIsTxTime = false;
303 strFromAccount.clear();
305 fDebitCached = false;
306 fCreditCached = false;
307 fAvailableCreditCached = false;
308 fChangeCached = false;
311 nAvailableCreditCached = 0;
315 fConfirmedDisplayed = false;
320 CWalletTx* pthis = const_cast<CWalletTx*>(this);
327 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
330 BOOST_FOREACH(char f, vfSpent)
332 str += (f ? '1' : '0');
336 pthis->mapValue["spent"] = str;
339 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
342 READWRITE(vOrderForm);
343 READWRITE(fTimeReceivedIsTxTime);
344 READWRITE(nTimeReceived);
350 pthis->strFromAccount = pthis->mapValue["fromaccount"];
352 if (mapValue.count("spent"))
353 BOOST_FOREACH(char c, pthis->mapValue["spent"])
354 pthis->vfSpent.push_back(c != '0');
356 pthis->vfSpent.assign(vout.size(), fSpent);
359 pthis->mapValue.erase("fromaccount");
360 pthis->mapValue.erase("version");
361 pthis->mapValue.erase("spent");
364 // marks certain txout's as spent
365 // returns true if any update took place
366 bool UpdateSpent(const std::vector<char>& vfNewSpent)
368 bool fReturn = false;
369 for (int i=0; i < vfNewSpent.size(); i++)
371 if (i == vfSpent.size())
374 if (vfNewSpent[i] && !vfSpent[i])
378 fAvailableCreditCached = false;
384 // make sure balances are recalculated
387 fCreditCached = false;
388 fAvailableCreditCached = false;
389 fDebitCached = false;
390 fChangeCached = false;
393 void BindWallet(CWallet *pwalletIn)
399 void MarkSpent(unsigned int nOut)
401 if (nOut >= vout.size())
402 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
403 vfSpent.resize(vout.size());
406 vfSpent[nOut] = true;
407 fAvailableCreditCached = false;
411 bool IsSpent(unsigned int nOut) const
413 if (nOut >= vout.size())
414 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
415 if (nOut >= vfSpent.size())
417 return (!!vfSpent[nOut]);
420 int64 GetDebit() const
426 nDebitCached = pwallet->GetDebit(*this);
431 int64 GetCredit(bool fUseCache=true) const
433 // Must wait until coinbase is safely deep enough in the chain before valuing it
434 if (IsCoinBase() && GetBlocksToMaturity() > 0)
437 // GetBalance can assume transactions in mapWallet won't change
438 if (fUseCache && fCreditCached)
439 return nCreditCached;
440 nCreditCached = pwallet->GetCredit(*this);
441 fCreditCached = true;
442 return nCreditCached;
445 int64 GetAvailableCredit(bool fUseCache=true) const
447 // Must wait until coinbase is safely deep enough in the chain before valuing it
448 if (IsCoinBase() && GetBlocksToMaturity() > 0)
451 if (fUseCache && fAvailableCreditCached)
452 return nAvailableCreditCached;
455 for (int i = 0; i < vout.size(); i++)
459 const CTxOut &txout = vout[i];
460 nCredit += pwallet->GetCredit(txout);
461 if (!MoneyRange(nCredit))
462 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
466 nAvailableCreditCached = nCredit;
467 fAvailableCreditCached = true;
472 int64 GetChange() const
475 return nChangeCached;
476 nChangeCached = pwallet->GetChange(*this);
477 fChangeCached = true;
478 return nChangeCached;
481 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
482 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
484 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
485 int64& nSent, int64& nFee) const;
487 bool IsFromMe() const
489 return (GetDebit() > 0);
492 bool IsConfirmed() const
494 // Quick answer in most cases
497 if (GetDepthInMainChain() >= 1)
499 if (!IsFromMe()) // using wtx's cached debit
502 // If no confirmations but it's from us, we can still
503 // consider it confirmed if all dependencies are confirmed
504 std::map<uint256, const CMerkleTx*> mapPrev;
505 std::vector<const CMerkleTx*> vWorkQueue;
506 vWorkQueue.reserve(vtxPrev.size()+1);
507 vWorkQueue.push_back(this);
508 for (int i = 0; i < vWorkQueue.size(); i++)
510 const CMerkleTx* ptx = vWorkQueue[i];
514 if (ptx->GetDepthInMainChain() >= 1)
516 if (!pwallet->IsFromMe(*ptx))
520 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
521 mapPrev[tx.GetHash()] = &tx;
523 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
525 if (!mapPrev.count(txin.prevout.hash))
527 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
535 int64 GetTxTime() const;
536 int GetRequestCount() const;
538 void AddSupportingTransactions(CTxDB& txdb);
540 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
541 bool AcceptWalletTransaction();
543 void RelayWalletTransaction(CTxDB& txdb);
544 void RelayWalletTransaction();
549 // Private key that includes an expiration date in case it never gets used.
557 std::string strComment;
558 //// todo: add something to note what created it (user, getnewaddress, change)
559 //// maybe should have a map<string, string> property map
561 CWalletKey(int64 nExpires=0)
563 nTimeCreated = (nExpires ? GetTime() : 0);
564 nTimeExpires = nExpires;
569 if (!(nType & SER_GETHASH))
571 READWRITE(vchPrivKey);
572 READWRITE(nTimeCreated);
573 READWRITE(nTimeExpires);
574 READWRITE(strComment);
584 // Account information.
585 // Stored in wallet with key "acc"+string account name
590 std::vector<unsigned char> vchPubKey;
604 if (!(nType & SER_GETHASH))
606 READWRITE(vchPubKey);
613 // Internal transfers.
614 // Database key is acentry<account><counter>
616 class CAccountingEntry
619 std::string strAccount;
622 std::string strOtherAccount;
623 std::string strComment;
635 strOtherAccount.clear();
641 if (!(nType & SER_GETHASH))
643 // Note: strAccount is serialized as part of the key, not here.
644 READWRITE(nCreditDebit);
646 READWRITE(strOtherAccount);
647 READWRITE(strComment);
651 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);