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
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 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
78 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
79 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
80 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
81 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
85 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
86 void KeepKey(int64 nIndex);
87 void ReturnKey(int64 nIndex);
88 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
89 int64 GetOldestKeyPoolTime();
91 bool IsMine(const CTxIn& txin) const;
92 int64 GetDebit(const CTxIn& txin) const;
93 bool IsMine(const CTxOut& txout) const
95 return ::IsMine(*this, txout.scriptPubKey);
97 int64 GetCredit(const CTxOut& txout) const
99 if (!MoneyRange(txout.nValue))
100 throw std::runtime_error("CWallet::GetCredit() : value out of range");
101 return (IsMine(txout) ? txout.nValue : 0);
103 bool IsChange(const CTxOut& txout) const
105 CBitcoinAddress address;
106 if (ExtractAddress(txout.scriptPubKey, this, address))
107 CRITICAL_BLOCK(cs_wallet)
108 if (!mapAddressBook.count(address))
112 int64 GetChange(const CTxOut& txout) const
114 if (!MoneyRange(txout.nValue))
115 throw std::runtime_error("CWallet::GetChange() : value out of range");
116 return (IsChange(txout) ? txout.nValue : 0);
118 bool IsMine(const CTransaction& tx) const
120 BOOST_FOREACH(const CTxOut& txout, tx.vout)
125 bool IsFromMe(const CTransaction& tx) const
127 return (GetDebit(tx) > 0);
129 int64 GetDebit(const CTransaction& tx) const
132 BOOST_FOREACH(const CTxIn& txin, tx.vin)
134 nDebit += GetDebit(txin);
135 if (!MoneyRange(nDebit))
136 throw std::runtime_error("CWallet::GetDebit() : value out of range");
140 int64 GetCredit(const CTransaction& tx) const
143 BOOST_FOREACH(const CTxOut& txout, tx.vout)
145 nCredit += GetCredit(txout);
146 if (!MoneyRange(nCredit))
147 throw std::runtime_error("CWallet::GetCredit() : value out of range");
151 int64 GetChange(const CTransaction& tx) const
154 BOOST_FOREACH(const CTxOut& txout, tx.vout)
156 nChange += GetChange(txout);
157 if (!MoneyRange(nChange))
158 throw std::runtime_error("CWallet::GetChange() : value out of range");
162 void SetBestChain(const CBlockLocator& loc)
164 CWalletDB walletdb(strWalletFile);
165 walletdb.WriteBestBlock(loc);
168 int LoadWallet(bool& fFirstRunRet);
169 // bool BackupWallet(const std::string& strDest);
171 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
173 bool DelAddressBookName(const CBitcoinAddress& address);
175 void UpdatedTransaction(const uint256 &hashTx)
177 CRITICAL_BLOCK(cs_wallet)
178 vWalletUpdated.push_back(hashTx);
181 void PrintWallet(const CBlock& block);
183 void Inventory(const uint256 &hash)
185 CRITICAL_BLOCK(cs_wallet)
187 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
188 if (mi != mapRequestCount.end())
195 return setKeyPool.size();
198 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
200 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
209 std::vector<unsigned char> vchPubKey;
211 CReserveKey(CWallet* pwalletIn)
224 std::vector<unsigned char> GetReservedKey();
230 // A transaction with a bunch of additional info that only the owner cares
231 // about. It includes any unrecorded transactions needed to link it back
232 // to the block chain.
234 class CWalletTx : public CMerkleTx
237 const CWallet* pwallet;
239 std::vector<CMerkleTx> vtxPrev;
240 std::map<std::string, std::string> mapValue;
241 std::vector<std::pair<std::string, std::string> > vOrderForm;
242 unsigned int fTimeReceivedIsTxTime;
243 unsigned int nTimeReceived; // time received by this node
245 std::string strFromAccount;
246 std::vector<char> vfSpent;
249 mutable char fDebitCached;
250 mutable char fCreditCached;
251 mutable char fAvailableCreditCached;
252 mutable char fChangeCached;
253 mutable int64 nDebitCached;
254 mutable int64 nCreditCached;
255 mutable int64 nAvailableCreditCached;
256 mutable int64 nChangeCached;
258 // memory only UI hints
259 mutable unsigned int nTimeDisplayed;
260 mutable int nLinesDisplayed;
261 mutable char fConfirmedDisplayed;
268 CWalletTx(const CWallet* pwalletIn)
273 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
278 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
283 void Init(const CWallet* pwalletIn)
289 fTimeReceivedIsTxTime = false;
292 strFromAccount.clear();
294 fDebitCached = false;
295 fCreditCached = false;
296 fAvailableCreditCached = false;
297 fChangeCached = false;
300 nAvailableCreditCached = 0;
304 fConfirmedDisplayed = false;
309 CWalletTx* pthis = const_cast<CWalletTx*>(this);
316 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
319 BOOST_FOREACH(char f, vfSpent)
321 str += (f ? '1' : '0');
325 pthis->mapValue["spent"] = str;
328 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
331 READWRITE(vOrderForm);
332 READWRITE(fTimeReceivedIsTxTime);
333 READWRITE(nTimeReceived);
339 pthis->strFromAccount = pthis->mapValue["fromaccount"];
341 if (mapValue.count("spent"))
342 BOOST_FOREACH(char c, pthis->mapValue["spent"])
343 pthis->vfSpent.push_back(c != '0');
345 pthis->vfSpent.assign(vout.size(), fSpent);
348 pthis->mapValue.erase("fromaccount");
349 pthis->mapValue.erase("version");
350 pthis->mapValue.erase("spent");
353 // marks certain txout's as spent
354 // returns true if any update took place
355 bool UpdateSpent(const std::vector<char>& vfNewSpent)
357 bool fReturn = false;
358 for (int i=0; i < vfNewSpent.size(); i++)
360 if (i == vfSpent.size())
363 if (vfNewSpent[i] && !vfSpent[i])
367 fAvailableCreditCached = false;
375 fCreditCached = false;
376 fAvailableCreditCached = false;
377 fDebitCached = false;
378 fChangeCached = false;
381 void MarkSpent(unsigned int nOut)
383 if (nOut >= vout.size())
384 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
385 vfSpent.resize(vout.size());
388 vfSpent[nOut] = true;
389 fAvailableCreditCached = false;
393 bool IsSpent(unsigned int nOut) const
395 if (nOut >= vout.size())
396 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
397 if (nOut >= vfSpent.size())
399 return (!!vfSpent[nOut]);
402 int64 GetDebit() const
408 nDebitCached = pwallet->GetDebit(*this);
413 int64 GetCredit(bool fUseCache=true) const
415 // Must wait until coinbase is safely deep enough in the chain before valuing it
416 if (IsCoinBase() && GetBlocksToMaturity() > 0)
419 // GetBalance can assume transactions in mapWallet won't change
420 if (fUseCache && fCreditCached)
421 return nCreditCached;
422 nCreditCached = pwallet->GetCredit(*this);
423 fCreditCached = true;
424 return nCreditCached;
427 int64 GetAvailableCredit(bool fUseCache=true) const
429 // Must wait until coinbase is safely deep enough in the chain before valuing it
430 if (IsCoinBase() && GetBlocksToMaturity() > 0)
433 if (fUseCache && fAvailableCreditCached)
434 return nAvailableCreditCached;
437 for (int i = 0; i < vout.size(); i++)
441 const CTxOut &txout = vout[i];
442 nCredit += pwallet->GetCredit(txout);
443 if (!MoneyRange(nCredit))
444 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
448 nAvailableCreditCached = nCredit;
449 fAvailableCreditCached = true;
454 int64 GetChange() const
457 return nChangeCached;
458 nChangeCached = pwallet->GetChange(*this);
459 fChangeCached = true;
460 return nChangeCached;
463 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
464 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
466 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
467 int64& nSent, int64& nFee) const;
469 bool IsFromMe() const
471 return (GetDebit() > 0);
474 bool IsConfirmed() const
476 // Quick answer in most cases
479 if (GetDepthInMainChain() >= 1)
481 if (!IsFromMe()) // using wtx's cached debit
484 // If no confirmations but it's from us, we can still
485 // consider it confirmed if all dependencies are confirmed
486 std::map<uint256, const CMerkleTx*> mapPrev;
487 std::vector<const CMerkleTx*> vWorkQueue;
488 vWorkQueue.reserve(vtxPrev.size()+1);
489 vWorkQueue.push_back(this);
490 for (int i = 0; i < vWorkQueue.size(); i++)
492 const CMerkleTx* ptx = vWorkQueue[i];
496 if (ptx->GetDepthInMainChain() >= 1)
498 if (!pwallet->IsFromMe(*ptx))
502 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
503 mapPrev[tx.GetHash()] = &tx;
505 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
507 if (!mapPrev.count(txin.prevout.hash))
509 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
517 int64 GetTxTime() const;
518 int GetRequestCount() const;
520 void AddSupportingTransactions(CTxDB& txdb);
522 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
523 bool AcceptWalletTransaction();
525 void RelayWalletTransaction(CTxDB& txdb);
526 void RelayWalletTransaction();
531 // Private key that includes an expiration date in case it never gets used.
539 std::string strComment;
540 //// todo: add something to note what created it (user, getnewaddress, change)
541 //// maybe should have a map<string, string> property map
543 CWalletKey(int64 nExpires=0)
545 nTimeCreated = (nExpires ? GetTime() : 0);
546 nTimeExpires = nExpires;
551 if (!(nType & SER_GETHASH))
553 READWRITE(vchPrivKey);
554 READWRITE(nTimeCreated);
555 READWRITE(nTimeExpires);
556 READWRITE(strComment);
566 // Account information.
567 // Stored in wallet with key "acc"+string account name
572 std::vector<unsigned char> vchPubKey;
586 if (!(nType & SER_GETHASH))
588 READWRITE(vchPubKey);
595 // Internal transfers.
596 // Database key is acentry<account><counter>
598 class CAccountingEntry
601 std::string strAccount;
604 std::string strOtherAccount;
605 std::string strComment;
617 strOtherAccount.clear();
623 if (!(nType & SER_GETHASH))
625 // Note: strAccount is serialized as part of the key, not here.
626 READWRITE(nCreditDebit);
628 READWRITE(strOtherAccount);
629 READWRITE(strComment);
633 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);