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
19 // A CWallet is an extension of a keystore, which also maintains a set of
20 // transactions and balances, and provides the ability to create new
22 class CWallet : public CCryptoKeyStore
25 bool SelectCoinsMinConf(int64_t nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
26 bool SelectCoins(int64_t nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
28 CWalletDB *pwalletdbEncryption;
31 mutable CCriticalSection cs_wallet;
34 std::string strWalletFile;
36 std::set<int64_t> setKeyPool;
38 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
39 MasterKeyMap mapMasterKeys;
40 unsigned int nMasterKeyMaxID;
46 pwalletdbEncryption = NULL;
48 CWallet(std::string strWalletFileIn)
50 strWalletFile = strWalletFileIn;
53 pwalletdbEncryption = NULL;
56 std::map<uint256, CWalletTx> mapWallet;
57 std::vector<uint256> vWalletUpdated;
59 std::map<uint256, int> mapRequestCount;
61 std::map<CBitcoinAddress, std::string> mapAddressBook;
63 std::vector<unsigned char> vchDefaultKey;
65 // keystore implementation
66 // Adds a key to the store, and saves it to disk.
67 bool AddKey(const CKey& key);
68 // Adds a key to the store, without saving it to disk (used by LoadWallet)
69 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
71 // Adds an encrypted key to the store, and saves it to disk.
72 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
73 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
74 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
75 bool AddCScript(const uint160& hash, const CScript& redeemScript);
76 bool LoadCScript(const uint160& hash, const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(hash, redeemScript); }
78 bool Unlock(const SecureString& strWalletPassphrase);
79 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
80 bool EncryptWallet(const SecureString& strWalletPassphrase);
83 bool AddToWallet(const CWalletTx& wtxIn);
84 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
85 bool EraseFromWallet(uint256 hash);
86 void WalletUpdateSpent(const CTransaction& prevout);
87 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
88 int ScanForWalletTransaction(const uint256& hashTx);
89 void ReacceptWalletTransactions();
90 void ResendWalletTransactions();
91 int64_t GetBalance() const;
92 int64_t GetUnconfirmedBalance() const;
93 bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet);
94 bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet);
95 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
96 bool BroadcastTransaction(CWalletTx& wtxNew);
97 std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
98 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
102 int64_t AddReserveKey(const CKeyPool& keypool);
103 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
104 void KeepKey(int64_t nIndex);
105 void ReturnKey(int64_t nIndex);
106 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
107 int64_t GetOldestKeyPoolTime();
108 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
110 bool IsMine(const CTxIn& txin) const;
111 int64_t GetDebit(const CTxIn& txin) const;
112 bool IsMine(const CTxOut& txout) const
114 return ::IsMine(*this, txout.scriptPubKey);
116 int64_t GetCredit(const CTxOut& txout) const
118 if (!MoneyRange(txout.nValue))
119 throw std::runtime_error("CWallet::GetCredit() : value out of range");
120 return (IsMine(txout) ? txout.nValue : 0);
122 bool IsChange(const CTxOut& txout) const;
123 int64_t GetChange(const CTxOut& txout) const
125 if (!MoneyRange(txout.nValue))
126 throw std::runtime_error("CWallet::GetChange() : value out of range");
127 return (IsChange(txout) ? txout.nValue : 0);
129 bool IsMine(const CTransaction& tx) const
131 BOOST_FOREACH(const CTxOut& txout, tx.vout)
136 bool IsFromMe(const CTransaction& tx) const
138 return (GetDebit(tx) > 0);
140 int64_t GetDebit(const CTransaction& tx) const
143 BOOST_FOREACH(const CTxIn& txin, tx.vin)
145 nDebit += GetDebit(txin);
146 if (!MoneyRange(nDebit))
147 throw std::runtime_error("CWallet::GetDebit() : value out of range");
151 int64_t GetCredit(const CTransaction& tx) const
154 BOOST_FOREACH(const CTxOut& txout, tx.vout)
156 nCredit += GetCredit(txout);
157 if (!MoneyRange(nCredit))
158 throw std::runtime_error("CWallet::GetCredit() : value out of range");
162 int64_t GetChange(const CTransaction& tx) const
165 BOOST_FOREACH(const CTxOut& txout, tx.vout)
167 nChange += GetChange(txout);
168 if (!MoneyRange(nChange))
169 throw std::runtime_error("CWallet::GetChange() : value out of range");
173 void SetBestChain(const CBlockLocator& loc)
175 CWalletDB walletdb(strWalletFile);
176 walletdb.WriteBestBlock(loc);
179 int LoadWallet(bool& fFirstRunRet);
180 // bool BackupWallet(const std::string& strDest);
182 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
184 bool DelAddressBookName(const CBitcoinAddress& address);
186 void UpdatedTransaction(const uint256 &hashTx)
188 CRITICAL_BLOCK(cs_wallet)
189 vWalletUpdated.push_back(hashTx);
192 void PrintWallet(const CBlock& block);
194 void Inventory(const uint256 &hash)
196 CRITICAL_BLOCK(cs_wallet)
198 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
199 if (mi != mapRequestCount.end())
206 return setKeyPool.size();
209 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
211 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
220 std::vector<unsigned char> vchPubKey;
222 CReserveKey(CWallet* pwalletIn)
235 std::vector<unsigned char> GetReservedKey();
241 // A transaction with a bunch of additional info that only the owner cares
242 // about. It includes any unrecorded transactions needed to link it back
243 // to the block chain.
245 class CWalletTx : public CMerkleTx
248 const CWallet* pwallet;
251 std::vector<CMerkleTx> vtxPrev;
252 std::map<std::string, std::string> mapValue;
253 std::vector<std::pair<std::string, std::string> > vOrderForm;
254 unsigned int fTimeReceivedIsTxTime;
255 unsigned int nTimeReceived; // time received by this node
257 std::string strFromAccount;
258 std::vector<char> vfSpent; // which outputs are already spent
261 mutable char fDebitCached;
262 mutable char fCreditCached;
263 mutable char fAvailableCreditCached;
264 mutable char fChangeCached;
265 mutable int64_t nDebitCached;
266 mutable int64_t nCreditCached;
267 mutable int64_t nAvailableCreditCached;
268 mutable int64_t nChangeCached;
270 // memory only UI hints
271 mutable unsigned int nTimeDisplayed;
272 mutable int nLinesDisplayed;
273 mutable char fConfirmedDisplayed;
280 CWalletTx(const CWallet* pwalletIn)
285 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
290 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
295 void Init(const CWallet* pwalletIn)
301 fTimeReceivedIsTxTime = false;
304 strFromAccount.clear();
306 fDebitCached = false;
307 fCreditCached = false;
308 fAvailableCreditCached = false;
309 fChangeCached = false;
312 nAvailableCreditCached = 0;
316 fConfirmedDisplayed = false;
321 CWalletTx* pthis = const_cast<CWalletTx*>(this);
328 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
331 BOOST_FOREACH(char f, vfSpent)
333 str += (f ? '1' : '0');
337 pthis->mapValue["spent"] = str;
340 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
343 READWRITE(vOrderForm);
344 READWRITE(fTimeReceivedIsTxTime);
345 READWRITE(nTimeReceived);
351 pthis->strFromAccount = pthis->mapValue["fromaccount"];
353 if (mapValue.count("spent"))
354 BOOST_FOREACH(char c, pthis->mapValue["spent"])
355 pthis->vfSpent.push_back(c != '0');
357 pthis->vfSpent.assign(vout.size(), fSpent);
360 pthis->mapValue.erase("fromaccount");
361 pthis->mapValue.erase("version");
362 pthis->mapValue.erase("spent");
365 // marks certain txout's as spent
366 // returns true if any update took place
367 bool UpdateSpent(const std::vector<char>& vfNewSpent)
369 bool fReturn = false;
370 for (int i=0; i < vfNewSpent.size(); i++)
372 if (i == vfSpent.size())
375 if (vfNewSpent[i] && !vfSpent[i])
379 fAvailableCreditCached = false;
385 // make sure balances are recalculated
388 fCreditCached = false;
389 fAvailableCreditCached = false;
390 fDebitCached = false;
391 fChangeCached = false;
394 void BindWallet(CWallet *pwalletIn)
400 void MarkSpent(unsigned int nOut)
402 if (nOut >= vout.size())
403 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
404 vfSpent.resize(vout.size());
407 vfSpent[nOut] = true;
408 fAvailableCreditCached = false;
412 bool IsSpent(unsigned int nOut) const
414 if (nOut >= vout.size())
415 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
416 if (nOut >= vfSpent.size())
418 return (!!vfSpent[nOut]);
421 int64_t GetDebit() const
427 nDebitCached = pwallet->GetDebit(*this);
432 int64_t GetCredit(bool fUseCache=true) const
434 // Must wait until coinbase is safely deep enough in the chain before valuing it
435 if (IsCoinBase() && GetBlocksToMaturity() > 0)
438 // GetBalance can assume transactions in mapWallet won't change
439 if (fUseCache && fCreditCached)
440 return nCreditCached;
441 nCreditCached = pwallet->GetCredit(*this);
442 fCreditCached = true;
443 return nCreditCached;
446 int64_t GetAvailableCredit(bool fUseCache=true) const
448 // Must wait until coinbase is safely deep enough in the chain before valuing it
449 if (IsCoinBase() && GetBlocksToMaturity() > 0)
452 if (fUseCache && fAvailableCreditCached)
453 return nAvailableCreditCached;
456 for (int i = 0; i < vout.size(); i++)
460 const CTxOut &txout = vout[i];
461 nCredit += pwallet->GetCredit(txout);
462 if (!MoneyRange(nCredit))
463 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
467 nAvailableCreditCached = nCredit;
468 fAvailableCreditCached = true;
473 int64_t GetChange() const
476 return nChangeCached;
477 nChangeCached = pwallet->GetChange(*this);
478 fChangeCached = true;
479 return nChangeCached;
482 void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
483 std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount) const;
485 void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
486 int64_t& nSent, int64_t& nFee) const;
488 bool IsFromMe() const
490 return (GetDebit() > 0);
493 bool IsConfirmed() const
495 // Quick answer in most cases
498 if (GetDepthInMainChain() >= 1)
500 if (!IsFromMe()) // using wtx's cached debit
503 // If no confirmations but it's from us, we can still
504 // consider it confirmed if all dependencies are confirmed
505 std::map<uint256, const CMerkleTx*> mapPrev;
506 std::vector<const CMerkleTx*> vWorkQueue;
507 vWorkQueue.reserve(vtxPrev.size()+1);
508 vWorkQueue.push_back(this);
509 for (int i = 0; i < vWorkQueue.size(); i++)
511 const CMerkleTx* ptx = vWorkQueue[i];
515 if (ptx->GetDepthInMainChain() >= 1)
517 if (!pwallet->IsFromMe(*ptx))
521 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
522 mapPrev[tx.GetHash()] = &tx;
524 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
526 if (!mapPrev.count(txin.prevout.hash))
528 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
536 int64_t GetTxTime() const;
537 int GetRequestCount() const;
539 void AddSupportingTransactions(CTxDB& txdb);
541 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
542 bool AcceptWalletTransaction();
544 void RelayWalletTransaction(CTxDB& txdb);
545 void RelayWalletTransaction();
550 // Private key that includes an expiration date in case it never gets used.
556 int64_t nTimeCreated;
557 int64_t nTimeExpires;
558 std::string strComment;
559 //// todo: add something to note what created it (user, getnewaddress, change)
560 //// maybe should have a map<string, string> property map
562 CWalletKey(int64_t nExpires=0)
564 nTimeCreated = (nExpires ? GetTime() : 0);
565 nTimeExpires = nExpires;
570 if (!(nType & SER_GETHASH))
572 READWRITE(vchPrivKey);
573 READWRITE(nTimeCreated);
574 READWRITE(nTimeExpires);
575 READWRITE(strComment);
585 // Account information.
586 // Stored in wallet with key "acc"+string account name
591 std::vector<unsigned char> vchPubKey;
605 if (!(nType & SER_GETHASH))
607 READWRITE(vchPubKey);
614 // Internal transfers.
615 // Database key is acentry<account><counter>
617 class CAccountingEntry
620 std::string strAccount;
621 int64_t nCreditDebit;
623 std::string strOtherAccount;
624 std::string strComment;
636 strOtherAccount.clear();
642 if (!(nType & SER_GETHASH))
644 // Note: strAccount is serialized as part of the key, not here.
645 READWRITE(nCreditDebit);
647 READWRITE(strOtherAccount);
648 READWRITE(strComment);
652 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);