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
17 // A CWallet is an extension of a keystore, which also maintains a set of
18 // transactions and balances, and provides the ability to create new
20 class CWallet : public CCryptoKeyStore
23 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
24 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
26 CWalletDB *pwalletdbEncryption;
29 mutable CCriticalSection cs_wallet;
32 std::string strWalletFile;
34 std::set<int64> setKeyPool;
36 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
37 MasterKeyMap mapMasterKeys;
38 unsigned int nMasterKeyMaxID;
44 pwalletdbEncryption = NULL;
46 CWallet(std::string strWalletFileIn)
48 strWalletFile = strWalletFileIn;
51 pwalletdbEncryption = NULL;
54 std::map<uint256, CWalletTx> mapWallet;
55 std::vector<uint256> vWalletUpdated;
57 std::map<uint256, int> mapRequestCount;
59 std::map<CBitcoinAddress, std::string> mapAddressBook;
61 std::vector<unsigned char> vchDefaultKey;
63 // keystore implementation
64 // Adds a key to the store, and saves it to disk.
65 bool AddKey(const CKey& key);
66 // Adds a key to the store, without saving it to disk (used by LoadWallet)
67 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
69 // Adds an encrypted key to the store, and saves it to disk.
70 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
71 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
72 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
73 bool AddCScript(const uint160& hash, const CScript& redeemScript);
74 bool LoadCScript(const uint160& hash, const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(hash, redeemScript); }
76 bool Unlock(const SecureString& strWalletPassphrase);
77 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
78 bool EncryptWallet(const SecureString& strWalletPassphrase);
81 bool AddToWallet(const CWalletTx& wtxIn);
82 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
83 bool EraseFromWallet(uint256 hash);
84 void WalletUpdateSpent(const CTransaction& prevout);
85 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
86 int ScanForWalletTransaction(const uint256& hashTx);
87 void ReacceptWalletTransactions();
88 void ResendWalletTransactions();
89 int64 GetBalance() const;
90 int64 GetUnconfirmedBalance() const;
91 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
92 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
93 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
94 bool BroadcastTransaction(CWalletTx& wtxNew);
95 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
96 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
100 int64 AddReserveKey(const CKeyPool& keypool);
101 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
102 void KeepKey(int64 nIndex);
103 void ReturnKey(int64 nIndex);
104 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
105 int64 GetOldestKeyPoolTime();
106 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
108 bool IsMine(const CTxIn& txin) const;
109 int64 GetDebit(const CTxIn& txin) const;
110 bool IsMine(const CTxOut& txout) const
112 return ::IsMine(*this, txout.scriptPubKey);
114 int64 GetCredit(const CTxOut& txout) const
116 if (!MoneyRange(txout.nValue))
117 throw std::runtime_error("CWallet::GetCredit() : value out of range");
118 return (IsMine(txout) ? txout.nValue : 0);
120 bool IsChange(const CTxOut& txout) const;
121 int64 GetChange(const CTxOut& txout) const
123 if (!MoneyRange(txout.nValue))
124 throw std::runtime_error("CWallet::GetChange() : value out of range");
125 return (IsChange(txout) ? txout.nValue : 0);
127 bool IsMine(const CTransaction& tx) const
129 BOOST_FOREACH(const CTxOut& txout, tx.vout)
134 bool IsFromMe(const CTransaction& tx) const
136 return (GetDebit(tx) > 0);
138 int64 GetDebit(const CTransaction& tx) const
141 BOOST_FOREACH(const CTxIn& txin, tx.vin)
143 nDebit += GetDebit(txin);
144 if (!MoneyRange(nDebit))
145 throw std::runtime_error("CWallet::GetDebit() : value out of range");
149 int64 GetCredit(const CTransaction& tx) const
152 BOOST_FOREACH(const CTxOut& txout, tx.vout)
154 nCredit += GetCredit(txout);
155 if (!MoneyRange(nCredit))
156 throw std::runtime_error("CWallet::GetCredit() : value out of range");
160 int64 GetChange(const CTransaction& tx) const
163 BOOST_FOREACH(const CTxOut& txout, tx.vout)
165 nChange += GetChange(txout);
166 if (!MoneyRange(nChange))
167 throw std::runtime_error("CWallet::GetChange() : value out of range");
171 void SetBestChain(const CBlockLocator& loc)
173 CWalletDB walletdb(strWalletFile);
174 walletdb.WriteBestBlock(loc);
177 int LoadWallet(bool& fFirstRunRet);
178 // bool BackupWallet(const std::string& strDest);
180 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
182 bool DelAddressBookName(const CBitcoinAddress& address);
184 void UpdatedTransaction(const uint256 &hashTx)
186 CRITICAL_BLOCK(cs_wallet)
187 vWalletUpdated.push_back(hashTx);
190 void PrintWallet(const CBlock& block);
192 void Inventory(const uint256 &hash)
194 CRITICAL_BLOCK(cs_wallet)
196 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
197 if (mi != mapRequestCount.end())
204 return setKeyPool.size();
207 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
209 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
218 std::vector<unsigned char> vchPubKey;
220 CReserveKey(CWallet* pwalletIn)
233 std::vector<unsigned char> GetReservedKey();
239 // A transaction with a bunch of additional info that only the owner cares
240 // about. It includes any unrecorded transactions needed to link it back
241 // to the block chain.
243 class CWalletTx : public CMerkleTx
246 const CWallet* pwallet;
249 std::vector<CMerkleTx> vtxPrev;
250 std::map<std::string, std::string> mapValue;
251 std::vector<std::pair<std::string, std::string> > vOrderForm;
252 unsigned int fTimeReceivedIsTxTime;
253 unsigned int nTimeReceived; // time received by this node
255 std::string strFromAccount;
256 std::vector<char> vfSpent; // which outputs are already spent
259 mutable char fDebitCached;
260 mutable char fCreditCached;
261 mutable char fAvailableCreditCached;
262 mutable char fChangeCached;
263 mutable int64 nDebitCached;
264 mutable int64 nCreditCached;
265 mutable int64 nAvailableCreditCached;
266 mutable int64 nChangeCached;
268 // memory only UI hints
269 mutable unsigned int nTimeDisplayed;
270 mutable int nLinesDisplayed;
271 mutable char fConfirmedDisplayed;
278 CWalletTx(const CWallet* pwalletIn)
283 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
288 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
293 void Init(const CWallet* pwalletIn)
299 fTimeReceivedIsTxTime = false;
302 strFromAccount.clear();
304 fDebitCached = false;
305 fCreditCached = false;
306 fAvailableCreditCached = false;
307 fChangeCached = false;
310 nAvailableCreditCached = 0;
314 fConfirmedDisplayed = false;
319 CWalletTx* pthis = const_cast<CWalletTx*>(this);
326 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
329 BOOST_FOREACH(char f, vfSpent)
331 str += (f ? '1' : '0');
335 pthis->mapValue["spent"] = str;
338 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
341 READWRITE(vOrderForm);
342 READWRITE(fTimeReceivedIsTxTime);
343 READWRITE(nTimeReceived);
349 pthis->strFromAccount = pthis->mapValue["fromaccount"];
351 if (mapValue.count("spent"))
352 BOOST_FOREACH(char c, pthis->mapValue["spent"])
353 pthis->vfSpent.push_back(c != '0');
355 pthis->vfSpent.assign(vout.size(), fSpent);
358 pthis->mapValue.erase("fromaccount");
359 pthis->mapValue.erase("version");
360 pthis->mapValue.erase("spent");
363 // marks certain txout's as spent
364 // returns true if any update took place
365 bool UpdateSpent(const std::vector<char>& vfNewSpent)
367 bool fReturn = false;
368 for (int i=0; i < vfNewSpent.size(); i++)
370 if (i == vfSpent.size())
373 if (vfNewSpent[i] && !vfSpent[i])
377 fAvailableCreditCached = false;
383 // make sure balances are recalculated
386 fCreditCached = false;
387 fAvailableCreditCached = false;
388 fDebitCached = false;
389 fChangeCached = false;
392 void BindWallet(CWallet *pwalletIn)
398 void MarkSpent(unsigned int nOut)
400 if (nOut >= vout.size())
401 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
402 vfSpent.resize(vout.size());
405 vfSpent[nOut] = true;
406 fAvailableCreditCached = false;
410 bool IsSpent(unsigned int nOut) const
412 if (nOut >= vout.size())
413 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
414 if (nOut >= vfSpent.size())
416 return (!!vfSpent[nOut]);
419 int64 GetDebit() const
425 nDebitCached = pwallet->GetDebit(*this);
430 int64 GetCredit(bool fUseCache=true) const
432 // Must wait until coinbase is safely deep enough in the chain before valuing it
433 if (IsCoinBase() && GetBlocksToMaturity() > 0)
436 // GetBalance can assume transactions in mapWallet won't change
437 if (fUseCache && fCreditCached)
438 return nCreditCached;
439 nCreditCached = pwallet->GetCredit(*this);
440 fCreditCached = true;
441 return nCreditCached;
444 int64 GetAvailableCredit(bool fUseCache=true) const
446 // Must wait until coinbase is safely deep enough in the chain before valuing it
447 if (IsCoinBase() && GetBlocksToMaturity() > 0)
450 if (fUseCache && fAvailableCreditCached)
451 return nAvailableCreditCached;
454 for (int i = 0; i < vout.size(); i++)
458 const CTxOut &txout = vout[i];
459 nCredit += pwallet->GetCredit(txout);
460 if (!MoneyRange(nCredit))
461 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
465 nAvailableCreditCached = nCredit;
466 fAvailableCreditCached = true;
471 int64 GetChange() const
474 return nChangeCached;
475 nChangeCached = pwallet->GetChange(*this);
476 fChangeCached = true;
477 return nChangeCached;
480 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
481 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
483 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
484 int64& nSent, int64& nFee) const;
486 bool IsFromMe() const
488 return (GetDebit() > 0);
491 bool IsConfirmed() const
493 // Quick answer in most cases
496 if (GetDepthInMainChain() >= 1)
498 if (!IsFromMe()) // using wtx's cached debit
501 // If no confirmations but it's from us, we can still
502 // consider it confirmed if all dependencies are confirmed
503 std::map<uint256, const CMerkleTx*> mapPrev;
504 std::vector<const CMerkleTx*> vWorkQueue;
505 vWorkQueue.reserve(vtxPrev.size()+1);
506 vWorkQueue.push_back(this);
507 for (int i = 0; i < vWorkQueue.size(); i++)
509 const CMerkleTx* ptx = vWorkQueue[i];
513 if (ptx->GetDepthInMainChain() >= 1)
515 if (!pwallet->IsFromMe(*ptx))
519 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
520 mapPrev[tx.GetHash()] = &tx;
522 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
524 if (!mapPrev.count(txin.prevout.hash))
526 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
534 int64 GetTxTime() const;
535 int GetRequestCount() const;
537 void AddSupportingTransactions(CTxDB& txdb);
539 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
540 bool AcceptWalletTransaction();
542 void RelayWalletTransaction(CTxDB& txdb);
543 void RelayWalletTransaction();
548 // Private key that includes an expiration date in case it never gets used.
556 std::string strComment;
557 //// todo: add something to note what created it (user, getnewaddress, change)
558 //// maybe should have a map<string, string> property map
560 CWalletKey(int64 nExpires=0)
562 nTimeCreated = (nExpires ? GetTime() : 0);
563 nTimeExpires = nExpires;
568 if (!(nType & SER_GETHASH))
570 READWRITE(vchPrivKey);
571 READWRITE(nTimeCreated);
572 READWRITE(nTimeExpires);
573 READWRITE(strComment);
583 // Account information.
584 // Stored in wallet with key "acc"+string account name
589 std::vector<unsigned char> vchPubKey;
603 if (!(nType & SER_GETHASH))
605 READWRITE(vchPubKey);
612 // Internal transfers.
613 // Database key is acentry<account><counter>
615 class CAccountingEntry
618 std::string strAccount;
621 std::string strOtherAccount;
622 std::string strComment;
634 strOtherAccount.clear();
640 if (!(nType & SER_GETHASH))
642 // Note: strAccount is serialized as part of the key, not here.
643 READWRITE(nCreditDebit);
645 READWRITE(strOtherAccount);
646 READWRITE(strComment);
650 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);