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;
25 mutable CCriticalSection cs_wallet;
28 std::string strWalletFile;
30 std::set<int64> 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 std::map<uint256, CWalletTx> mapWallet;
51 std::vector<uint256> vWalletUpdated;
53 std::map<uint256, int> mapRequestCount;
55 std::map<CBitcoinAddress, std::string> mapAddressBook;
57 std::vector<unsigned char> vchDefaultKey;
59 // keystore implementation
60 bool AddKey(const CKey& key);
61 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
62 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
63 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
65 bool Unlock(const std::string& strWalletPassphrase);
66 bool ChangeWalletPassphrase(const std::string& strOldWalletPassphrase, const std::string& strNewWalletPassphrase);
67 bool EncryptWallet(const std::string& strWalletPassphrase);
69 bool AddToWallet(const CWalletTx& wtxIn);
70 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
71 bool EraseFromWallet(uint256 hash);
72 void WalletUpdateSpent(const CTransaction& prevout);
73 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
74 void ReacceptWalletTransactions();
75 void ResendWalletTransactions();
76 int64 GetBalance() const;
77 int64 GetUnconfirmedBalance() const;
78 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
79 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
80 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
81 bool BroadcastTransaction(CWalletTx& wtxNew);
82 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
83 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
86 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
87 void KeepKey(int64 nIndex);
88 void ReturnKey(int64 nIndex);
89 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
90 int64 GetOldestKeyPoolTime();
92 bool IsMine(const CTxIn& txin) const;
93 int64 GetDebit(const CTxIn& txin) const;
94 bool IsMine(const CTxOut& txout) const
96 return ::IsMine(*this, txout.scriptPubKey);
98 int64 GetCredit(const CTxOut& txout) const
100 if (!MoneyRange(txout.nValue))
101 throw std::runtime_error("CWallet::GetCredit() : value out of range");
102 return (IsMine(txout) ? txout.nValue : 0);
104 bool IsChange(const CTxOut& txout) const
106 CBitcoinAddress address;
107 if (ExtractAddress(txout.scriptPubKey, this, address))
108 CRITICAL_BLOCK(cs_wallet)
109 if (!mapAddressBook.count(address))
113 int64 GetChange(const CTxOut& txout) const
115 if (!MoneyRange(txout.nValue))
116 throw std::runtime_error("CWallet::GetChange() : value out of range");
117 return (IsChange(txout) ? txout.nValue : 0);
119 bool IsMine(const CTransaction& tx) const
121 BOOST_FOREACH(const CTxOut& txout, tx.vout)
126 bool IsFromMe(const CTransaction& tx) const
128 return (GetDebit(tx) > 0);
130 int64 GetDebit(const CTransaction& tx) const
133 BOOST_FOREACH(const CTxIn& txin, tx.vin)
135 nDebit += GetDebit(txin);
136 if (!MoneyRange(nDebit))
137 throw std::runtime_error("CWallet::GetDebit() : value out of range");
141 int64 GetCredit(const CTransaction& tx) const
144 BOOST_FOREACH(const CTxOut& txout, tx.vout)
146 nCredit += GetCredit(txout);
147 if (!MoneyRange(nCredit))
148 throw std::runtime_error("CWallet::GetCredit() : value out of range");
152 int64 GetChange(const CTransaction& tx) const
155 BOOST_FOREACH(const CTxOut& txout, tx.vout)
157 nChange += GetChange(txout);
158 if (!MoneyRange(nChange))
159 throw std::runtime_error("CWallet::GetChange() : value out of range");
163 void SetBestChain(const CBlockLocator& loc)
165 CWalletDB walletdb(strWalletFile);
166 walletdb.WriteBestBlock(loc);
169 int LoadWallet(bool& fFirstRunRet);
170 // bool BackupWallet(const std::string& strDest);
172 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
174 bool DelAddressBookName(const CBitcoinAddress& address);
176 void UpdatedTransaction(const uint256 &hashTx)
178 CRITICAL_BLOCK(cs_wallet)
179 vWalletUpdated.push_back(hashTx);
182 void PrintWallet(const CBlock& block);
184 void Inventory(const uint256 &hash)
186 CRITICAL_BLOCK(cs_wallet)
188 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
189 if (mi != mapRequestCount.end())
196 return setKeyPool.size();
199 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
201 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
210 std::vector<unsigned char> vchPubKey;
212 CReserveKey(CWallet* pwalletIn)
225 std::vector<unsigned char> GetReservedKey();
231 // A transaction with a bunch of additional info that only the owner cares
232 // about. It includes any unrecorded transactions needed to link it back
233 // to the block chain.
235 class CWalletTx : public CMerkleTx
238 const CWallet* pwallet;
240 std::vector<CMerkleTx> vtxPrev;
241 std::map<std::string, std::string> mapValue;
242 std::vector<std::pair<std::string, std::string> > vOrderForm;
243 unsigned int fTimeReceivedIsTxTime;
244 unsigned int nTimeReceived; // time received by this node
246 std::string strFromAccount;
247 std::vector<char> vfSpent;
250 mutable char fDebitCached;
251 mutable char fCreditCached;
252 mutable char fAvailableCreditCached;
253 mutable char fChangeCached;
254 mutable int64 nDebitCached;
255 mutable int64 nCreditCached;
256 mutable int64 nAvailableCreditCached;
257 mutable int64 nChangeCached;
259 // memory only UI hints
260 mutable unsigned int nTimeDisplayed;
261 mutable int nLinesDisplayed;
262 mutable char fConfirmedDisplayed;
269 CWalletTx(const CWallet* pwalletIn)
274 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
279 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
284 void Init(const CWallet* pwalletIn)
290 fTimeReceivedIsTxTime = false;
293 strFromAccount.clear();
295 fDebitCached = false;
296 fCreditCached = false;
297 fAvailableCreditCached = false;
298 fChangeCached = false;
301 nAvailableCreditCached = 0;
305 fConfirmedDisplayed = false;
310 CWalletTx* pthis = const_cast<CWalletTx*>(this);
317 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
320 BOOST_FOREACH(char f, vfSpent)
322 str += (f ? '1' : '0');
326 pthis->mapValue["spent"] = str;
329 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
332 READWRITE(vOrderForm);
333 READWRITE(fTimeReceivedIsTxTime);
334 READWRITE(nTimeReceived);
340 pthis->strFromAccount = pthis->mapValue["fromaccount"];
342 if (mapValue.count("spent"))
343 BOOST_FOREACH(char c, pthis->mapValue["spent"])
344 pthis->vfSpent.push_back(c != '0');
346 pthis->vfSpent.assign(vout.size(), fSpent);
349 pthis->mapValue.erase("fromaccount");
350 pthis->mapValue.erase("version");
351 pthis->mapValue.erase("spent");
354 // marks certain txout's as spent
355 // returns true if any update took place
356 bool UpdateSpent(const std::vector<char>& vfNewSpent)
358 bool fReturn = false;
359 for (int i=0; i < vfNewSpent.size(); i++)
361 if (i == vfSpent.size())
364 if (vfNewSpent[i] && !vfSpent[i])
368 fAvailableCreditCached = false;
376 fCreditCached = false;
377 fAvailableCreditCached = false;
378 fDebitCached = false;
379 fChangeCached = false;
382 void MarkSpent(unsigned int nOut)
384 if (nOut >= vout.size())
385 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
386 vfSpent.resize(vout.size());
389 vfSpent[nOut] = true;
390 fAvailableCreditCached = false;
394 bool IsSpent(unsigned int nOut) const
396 if (nOut >= vout.size())
397 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
398 if (nOut >= vfSpent.size())
400 return (!!vfSpent[nOut]);
403 int64 GetDebit() const
409 nDebitCached = pwallet->GetDebit(*this);
414 int64 GetCredit(bool fUseCache=true) const
416 // Must wait until coinbase is safely deep enough in the chain before valuing it
417 if (IsCoinBase() && GetBlocksToMaturity() > 0)
420 // GetBalance can assume transactions in mapWallet won't change
421 if (fUseCache && fCreditCached)
422 return nCreditCached;
423 nCreditCached = pwallet->GetCredit(*this);
424 fCreditCached = true;
425 return nCreditCached;
428 int64 GetAvailableCredit(bool fUseCache=true) const
430 // Must wait until coinbase is safely deep enough in the chain before valuing it
431 if (IsCoinBase() && GetBlocksToMaturity() > 0)
434 if (fUseCache && fAvailableCreditCached)
435 return nAvailableCreditCached;
438 for (int i = 0; i < vout.size(); i++)
442 const CTxOut &txout = vout[i];
443 nCredit += pwallet->GetCredit(txout);
444 if (!MoneyRange(nCredit))
445 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
449 nAvailableCreditCached = nCredit;
450 fAvailableCreditCached = true;
455 int64 GetChange() const
458 return nChangeCached;
459 nChangeCached = pwallet->GetChange(*this);
460 fChangeCached = true;
461 return nChangeCached;
464 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
465 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
467 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
468 int64& nSent, int64& nFee) const;
470 bool IsFromMe() const
472 return (GetDebit() > 0);
475 bool IsConfirmed() const
477 // Quick answer in most cases
480 if (GetDepthInMainChain() >= 1)
482 if (!IsFromMe()) // using wtx's cached debit
485 // If no confirmations but it's from us, we can still
486 // consider it confirmed if all dependencies are confirmed
487 std::map<uint256, const CMerkleTx*> mapPrev;
488 std::vector<const CMerkleTx*> vWorkQueue;
489 vWorkQueue.reserve(vtxPrev.size()+1);
490 vWorkQueue.push_back(this);
491 for (int i = 0; i < vWorkQueue.size(); i++)
493 const CMerkleTx* ptx = vWorkQueue[i];
497 if (ptx->GetDepthInMainChain() >= 1)
499 if (!pwallet->IsFromMe(*ptx))
503 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
504 mapPrev[tx.GetHash()] = &tx;
506 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
508 if (!mapPrev.count(txin.prevout.hash))
510 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
518 int64 GetTxTime() const;
519 int GetRequestCount() const;
521 void AddSupportingTransactions(CTxDB& txdb);
523 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
524 bool AcceptWalletTransaction();
526 void RelayWalletTransaction(CTxDB& txdb);
527 void RelayWalletTransaction();
532 // Private key that includes an expiration date in case it never gets used.
540 std::string strComment;
541 //// todo: add something to note what created it (user, getnewaddress, change)
542 //// maybe should have a map<string, string> property map
544 CWalletKey(int64 nExpires=0)
546 nTimeCreated = (nExpires ? GetTime() : 0);
547 nTimeExpires = nExpires;
552 if (!(nType & SER_GETHASH))
554 READWRITE(vchPrivKey);
555 READWRITE(nTimeCreated);
556 READWRITE(nTimeExpires);
557 READWRITE(strComment);
567 // Account information.
568 // Stored in wallet with key "acc"+string account name
573 std::vector<unsigned char> vchPubKey;
587 if (!(nType & SER_GETHASH))
589 READWRITE(vchPubKey);
596 // Internal transfers.
597 // Database key is acentry<account><counter>
599 class CAccountingEntry
602 std::string strAccount;
605 std::string strOtherAccount;
606 std::string strComment;
618 strOtherAccount.clear();
624 if (!(nType & SER_GETHASH))
626 // Note: strAccount is serialized as part of the key, not here.
627 READWRITE(nCreditDebit);
629 READWRITE(strOtherAccount);
630 READWRITE(strComment);
634 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);