1 // Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
4 #ifndef BITCOIN_WALLET_H
5 #define BITCOIN_WALLET_H
15 class CWallet : public CCryptoKeyStore
18 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
19 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
21 CWalletDB *pwalletdbEncryption;
22 CCriticalSection cs_pwalletdbEncryption;
26 std::string strWalletFile;
28 std::set<int64> setKeyPool;
29 CCriticalSection cs_setKeyPool;
31 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
32 MasterKeyMap mapMasterKeys;
33 unsigned int nMasterKeyMaxID;
39 pwalletdbEncryption = NULL;
41 CWallet(std::string strWalletFileIn)
43 strWalletFile = strWalletFileIn;
46 pwalletdbEncryption = NULL;
49 mutable CCriticalSection cs_mapWallet;
50 std::map<uint256, CWalletTx> mapWallet;
51 std::vector<uint256> vWalletUpdated;
53 std::map<uint256, int> mapRequestCount;
54 mutable CCriticalSection cs_mapRequestCount;
56 std::map<std::string, std::string> mapAddressBook;
57 mutable CCriticalSection cs_mapAddressBook;
59 std::vector<unsigned char> vchDefaultKey;
61 // keystore implementation
62 bool AddKey(const CKey& key);
63 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
64 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
65 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
67 bool Unlock(const std::string& strWalletPassphrase);
68 bool ChangeWalletPassphrase(const std::string& strOldWalletPassphrase, const std::string& strNewWalletPassphrase);
69 bool EncryptWallet(const std::string& strWalletPassphrase);
71 bool AddToWallet(const CWalletTx& wtxIn);
72 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
73 bool EraseFromWallet(uint256 hash);
74 void WalletUpdateSpent(const CTransaction& prevout);
75 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
76 void ReacceptWalletTransactions();
77 void ResendWalletTransactions();
78 int64 GetBalance() const;
79 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
80 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
81 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
82 bool BroadcastTransaction(CWalletTx& wtxNew);
83 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
84 std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
87 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
88 void KeepKey(int64 nIndex);
89 void ReturnKey(int64 nIndex);
90 std::vector<unsigned char> GetOrReuseKeyFromPool();
91 int64 GetOldestKeyPoolTime();
93 bool IsMine(const CTxIn& txin) const;
94 int64 GetDebit(const CTxIn& txin) const;
95 bool IsMine(const CTxOut& txout) const
97 return ::IsMine(*this, txout.scriptPubKey);
99 int64 GetCredit(const CTxOut& txout) const
101 if (!MoneyRange(txout.nValue))
102 throw std::runtime_error("CWallet::GetCredit() : value out of range");
103 return (IsMine(txout) ? txout.nValue : 0);
105 bool IsChange(const CTxOut& txout) const
107 std::vector<unsigned char> vchPubKey;
108 if (ExtractPubKey(txout.scriptPubKey, this, vchPubKey))
109 CRITICAL_BLOCK(cs_mapAddressBook)
110 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
114 int64 GetChange(const CTxOut& txout) const
116 if (!MoneyRange(txout.nValue))
117 throw std::runtime_error("CWallet::GetChange() : value out of range");
118 return (IsChange(txout) ? txout.nValue : 0);
120 bool IsMine(const CTransaction& tx) const
122 BOOST_FOREACH(const CTxOut& txout, tx.vout)
127 bool IsFromMe(const CTransaction& tx) const
129 return (GetDebit(tx) > 0);
131 int64 GetDebit(const CTransaction& tx) const
134 BOOST_FOREACH(const CTxIn& txin, tx.vin)
136 nDebit += GetDebit(txin);
137 if (!MoneyRange(nDebit))
138 throw std::runtime_error("CWallet::GetDebit() : value out of range");
142 int64 GetCredit(const CTransaction& tx) const
145 BOOST_FOREACH(const CTxOut& txout, tx.vout)
147 nCredit += GetCredit(txout);
148 if (!MoneyRange(nCredit))
149 throw std::runtime_error("CWallet::GetCredit() : value out of range");
153 int64 GetChange(const CTransaction& tx) const
156 BOOST_FOREACH(const CTxOut& txout, tx.vout)
158 nChange += GetChange(txout);
159 if (!MoneyRange(nChange))
160 throw std::runtime_error("CWallet::GetChange() : value out of range");
164 void SetBestChain(const CBlockLocator& loc)
166 CWalletDB walletdb(strWalletFile);
167 walletdb.WriteBestBlock(loc);
170 int LoadWallet(bool& fFirstRunRet);
171 // bool BackupWallet(const std::string& strDest);
173 // requires cs_mapAddressBook lock
174 bool SetAddressBookName(const std::string& strAddress, const std::string& strName);
176 // requires cs_mapAddressBook lock
177 bool DelAddressBookName(const std::string& strAddress);
179 void UpdatedTransaction(const uint256 &hashTx)
181 CRITICAL_BLOCK(cs_mapWallet)
182 vWalletUpdated.push_back(hashTx);
185 void PrintWallet(const CBlock& block);
187 void Inventory(const uint256 &hash)
189 CRITICAL_BLOCK(cs_mapRequestCount)
191 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
192 if (mi != mapRequestCount.end())
199 return setKeyPool.size();
202 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
204 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
213 std::vector<unsigned char> vchPubKey;
215 CReserveKey(CWallet* pwalletIn)
228 std::vector<unsigned char> GetReservedKey();
234 // A transaction with a bunch of additional info that only the owner cares
235 // about. It includes any unrecorded transactions needed to link it back
236 // to the block chain.
238 class CWalletTx : public CMerkleTx
241 const CWallet* pwallet;
243 std::vector<CMerkleTx> vtxPrev;
244 std::map<std::string, std::string> mapValue;
245 std::vector<std::pair<std::string, std::string> > vOrderForm;
246 unsigned int fTimeReceivedIsTxTime;
247 unsigned int nTimeReceived; // time received by this node
249 std::string strFromAccount;
250 std::vector<char> vfSpent;
253 mutable char fDebitCached;
254 mutable char fCreditCached;
255 mutable char fAvailableCreditCached;
256 mutable char fChangeCached;
257 mutable int64 nDebitCached;
258 mutable int64 nCreditCached;
259 mutable int64 nAvailableCreditCached;
260 mutable int64 nChangeCached;
262 // memory only UI hints
263 mutable unsigned int nTimeDisplayed;
264 mutable int nLinesDisplayed;
265 mutable char fConfirmedDisplayed;
272 CWalletTx(const CWallet* pwalletIn)
277 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
282 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
287 void Init(const CWallet* pwalletIn)
293 fTimeReceivedIsTxTime = false;
296 strFromAccount.clear();
298 fDebitCached = false;
299 fCreditCached = false;
300 fAvailableCreditCached = false;
301 fChangeCached = false;
304 nAvailableCreditCached = 0;
308 fConfirmedDisplayed = false;
313 CWalletTx* pthis = const_cast<CWalletTx*>(this);
320 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
323 BOOST_FOREACH(char f, vfSpent)
325 str += (f ? '1' : '0');
329 pthis->mapValue["spent"] = str;
332 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
335 READWRITE(vOrderForm);
336 READWRITE(fTimeReceivedIsTxTime);
337 READWRITE(nTimeReceived);
343 pthis->strFromAccount = pthis->mapValue["fromaccount"];
345 if (mapValue.count("spent"))
346 BOOST_FOREACH(char c, pthis->mapValue["spent"])
347 pthis->vfSpent.push_back(c != '0');
349 pthis->vfSpent.assign(vout.size(), fSpent);
352 pthis->mapValue.erase("fromaccount");
353 pthis->mapValue.erase("version");
354 pthis->mapValue.erase("spent");
357 // marks certain txout's as spent
358 // returns true if any update took place
359 bool UpdateSpent(const std::vector<char>& vfNewSpent)
361 bool fReturn = false;
362 for (int i=0; i < vfNewSpent.size(); i++)
364 if (i == vfSpent.size())
367 if (vfNewSpent[i] && !vfSpent[i])
371 fAvailableCreditCached = false;
379 fCreditCached = false;
380 fAvailableCreditCached = false;
381 fDebitCached = false;
382 fChangeCached = false;
385 void MarkSpent(unsigned int nOut)
387 if (nOut >= vout.size())
388 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
389 vfSpent.resize(vout.size());
392 vfSpent[nOut] = true;
393 fAvailableCreditCached = false;
397 bool IsSpent(unsigned int nOut) const
399 if (nOut >= vout.size())
400 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
401 if (nOut >= vfSpent.size())
403 return (!!vfSpent[nOut]);
406 int64 GetDebit() const
412 nDebitCached = pwallet->GetDebit(*this);
417 int64 GetCredit(bool fUseCache=true) const
419 // Must wait until coinbase is safely deep enough in the chain before valuing it
420 if (IsCoinBase() && GetBlocksToMaturity() > 0)
423 // GetBalance can assume transactions in mapWallet won't change
424 if (fUseCache && fCreditCached)
425 return nCreditCached;
426 nCreditCached = pwallet->GetCredit(*this);
427 fCreditCached = true;
428 return nCreditCached;
431 int64 GetAvailableCredit(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 if (fUseCache && fAvailableCreditCached)
438 return nAvailableCreditCached;
441 for (int i = 0; i < vout.size(); i++)
445 const CTxOut &txout = vout[i];
446 nCredit += pwallet->GetCredit(txout);
447 if (!MoneyRange(nCredit))
448 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
452 nAvailableCreditCached = nCredit;
453 fAvailableCreditCached = true;
458 int64 GetChange() const
461 return nChangeCached;
462 nChangeCached = pwallet->GetChange(*this);
463 fChangeCached = true;
464 return nChangeCached;
467 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
468 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
470 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
471 int64& nSent, int64& nFee) const;
473 bool IsFromMe() const
475 return (GetDebit() > 0);
478 bool IsConfirmed() const
480 // Quick answer in most cases
483 if (GetDepthInMainChain() >= 1)
485 if (!IsFromMe()) // using wtx's cached debit
488 // If no confirmations but it's from us, we can still
489 // consider it confirmed if all dependencies are confirmed
490 std::map<uint256, const CMerkleTx*> mapPrev;
491 std::vector<const CMerkleTx*> vWorkQueue;
492 vWorkQueue.reserve(vtxPrev.size()+1);
493 vWorkQueue.push_back(this);
494 for (int i = 0; i < vWorkQueue.size(); i++)
496 const CMerkleTx* ptx = vWorkQueue[i];
500 if (ptx->GetDepthInMainChain() >= 1)
502 if (!pwallet->IsFromMe(*ptx))
506 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
507 mapPrev[tx.GetHash()] = &tx;
509 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
511 if (!mapPrev.count(txin.prevout.hash))
513 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
521 int64 GetTxTime() const;
522 int GetRequestCount() const;
524 void AddSupportingTransactions(CTxDB& txdb);
526 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
527 bool AcceptWalletTransaction();
529 void RelayWalletTransaction(CTxDB& txdb);
530 void RelayWalletTransaction();
535 // Private key that includes an expiration date in case it never gets used.
543 std::string strComment;
544 //// todo: add something to note what created it (user, getnewaddress, change)
545 //// maybe should have a map<string, string> property map
547 CWalletKey(int64 nExpires=0)
549 nTimeCreated = (nExpires ? GetTime() : 0);
550 nTimeExpires = nExpires;
555 if (!(nType & SER_GETHASH))
557 READWRITE(vchPrivKey);
558 READWRITE(nTimeCreated);
559 READWRITE(nTimeExpires);
560 READWRITE(strComment);
570 // Account information.
571 // Stored in wallet with key "acc"+string account name
576 std::vector<unsigned char> vchPubKey;
590 if (!(nType & SER_GETHASH))
592 READWRITE(vchPubKey);
599 // Internal transfers.
600 // Database key is acentry<account><counter>
602 class CAccountingEntry
605 std::string strAccount;
608 std::string strOtherAccount;
609 std::string strComment;
621 strOtherAccount.clear();
627 if (!(nType & SER_GETHASH))
629 // Note: strAccount is serialized as part of the key, not here.
630 READWRITE(nCreditDebit);
632 READWRITE(strOtherAccount);
633 READWRITE(strComment);
637 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);