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);
170 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
172 bool DelAddressBookName(const CBitcoinAddress& address);
174 void UpdatedTransaction(const uint256 &hashTx)
176 CRITICAL_BLOCK(cs_wallet)
177 vWalletUpdated.push_back(hashTx);
180 void PrintWallet(const CBlock& block);
182 void Inventory(const uint256 &hash)
184 CRITICAL_BLOCK(cs_wallet)
186 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
187 if (mi != mapRequestCount.end())
194 return setKeyPool.size();
197 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
199 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
208 std::vector<unsigned char> vchPubKey;
210 CReserveKey(CWallet* pwalletIn)
223 std::vector<unsigned char> GetReservedKey();
229 // A transaction with a bunch of additional info that only the owner cares
230 // about. It includes any unrecorded transactions needed to link it back
231 // to the block chain.
233 class CWalletTx : public CMerkleTx
236 const CWallet* pwallet;
238 std::vector<CMerkleTx> vtxPrev;
239 std::map<std::string, std::string> mapValue;
240 std::vector<std::pair<std::string, std::string> > vOrderForm;
241 unsigned int fTimeReceivedIsTxTime;
242 unsigned int nTimeReceived; // time received by this node
244 std::string strFromAccount;
245 std::vector<char> vfSpent;
248 mutable char fDebitCached;
249 mutable char fCreditCached;
250 mutable char fAvailableCreditCached;
251 mutable char fChangeCached;
252 mutable int64 nDebitCached;
253 mutable int64 nCreditCached;
254 mutable int64 nAvailableCreditCached;
255 mutable int64 nChangeCached;
257 // memory only UI hints
258 mutable unsigned int nTimeDisplayed;
259 mutable int nLinesDisplayed;
260 mutable char fConfirmedDisplayed;
267 CWalletTx(const CWallet* pwalletIn)
272 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
277 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
282 void Init(const CWallet* pwalletIn)
288 fTimeReceivedIsTxTime = false;
291 strFromAccount.clear();
293 fDebitCached = false;
294 fCreditCached = false;
295 fAvailableCreditCached = false;
296 fChangeCached = false;
299 nAvailableCreditCached = 0;
303 fConfirmedDisplayed = false;
308 CWalletTx* pthis = const_cast<CWalletTx*>(this);
315 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
318 BOOST_FOREACH(char f, vfSpent)
320 str += (f ? '1' : '0');
324 pthis->mapValue["spent"] = str;
327 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
330 READWRITE(vOrderForm);
331 READWRITE(fTimeReceivedIsTxTime);
332 READWRITE(nTimeReceived);
338 pthis->strFromAccount = pthis->mapValue["fromaccount"];
340 if (mapValue.count("spent"))
341 BOOST_FOREACH(char c, pthis->mapValue["spent"])
342 pthis->vfSpent.push_back(c != '0');
344 pthis->vfSpent.assign(vout.size(), fSpent);
347 pthis->mapValue.erase("fromaccount");
348 pthis->mapValue.erase("version");
349 pthis->mapValue.erase("spent");
352 // marks certain txout's as spent
353 // returns true if any update took place
354 bool UpdateSpent(const std::vector<char>& vfNewSpent)
356 bool fReturn = false;
357 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
359 if (i == vfSpent.size())
362 if (vfNewSpent[i] && !vfSpent[i])
366 fAvailableCreditCached = false;
374 fCreditCached = false;
375 fAvailableCreditCached = false;
376 fDebitCached = false;
377 fChangeCached = false;
380 void MarkSpent(unsigned int nOut)
382 if (nOut >= vout.size())
383 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
384 vfSpent.resize(vout.size());
387 vfSpent[nOut] = true;
388 fAvailableCreditCached = false;
392 bool IsSpent(unsigned int nOut) const
394 if (nOut >= vout.size())
395 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
396 if (nOut >= vfSpent.size())
398 return (!!vfSpent[nOut]);
401 int64 GetDebit() const
407 nDebitCached = pwallet->GetDebit(*this);
412 int64 GetCredit(bool fUseCache=true) const
414 // Must wait until coinbase is safely deep enough in the chain before valuing it
415 if (IsCoinBase() && GetBlocksToMaturity() > 0)
418 // GetBalance can assume transactions in mapWallet won't change
419 if (fUseCache && fCreditCached)
420 return nCreditCached;
421 nCreditCached = pwallet->GetCredit(*this);
422 fCreditCached = true;
423 return nCreditCached;
426 int64 GetAvailableCredit(bool fUseCache=true) const
428 // Must wait until coinbase is safely deep enough in the chain before valuing it
429 if (IsCoinBase() && GetBlocksToMaturity() > 0)
432 if (fUseCache && fAvailableCreditCached)
433 return nAvailableCreditCached;
436 for (unsigned int i = 0; i < vout.size(); i++)
440 const CTxOut &txout = vout[i];
441 nCredit += pwallet->GetCredit(txout);
442 if (!MoneyRange(nCredit))
443 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
447 nAvailableCreditCached = nCredit;
448 fAvailableCreditCached = true;
453 int64 GetChange() const
456 return nChangeCached;
457 nChangeCached = pwallet->GetChange(*this);
458 fChangeCached = true;
459 return nChangeCached;
462 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
463 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
465 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
466 int64& nSent, int64& nFee) const;
468 bool IsFromMe() const
470 return (GetDebit() > 0);
473 bool IsConfirmed() const
475 // Quick answer in most cases
478 if (GetDepthInMainChain() >= 1)
480 if (!IsFromMe()) // using wtx's cached debit
483 // If no confirmations but it's from us, we can still
484 // consider it confirmed if all dependencies are confirmed
485 std::map<uint256, const CMerkleTx*> mapPrev;
486 std::vector<const CMerkleTx*> vWorkQueue;
487 vWorkQueue.reserve(vtxPrev.size()+1);
488 vWorkQueue.push_back(this);
489 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
491 const CMerkleTx* ptx = vWorkQueue[i];
495 if (ptx->GetDepthInMainChain() >= 1)
497 if (!pwallet->IsFromMe(*ptx))
502 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
503 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);