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
16 // A CWallet is an extension of a keystore, which also maintains a set of
17 // transactions and balances, and provides the ability to create new
19 class CWallet : public CCryptoKeyStore
22 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
23 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
25 CWalletDB *pwalletdbEncryption;
28 mutable CCriticalSection cs_wallet;
31 std::string strWalletFile;
33 std::set<int64> setKeyPool;
35 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
36 MasterKeyMap mapMasterKeys;
37 unsigned int nMasterKeyMaxID;
43 pwalletdbEncryption = NULL;
45 CWallet(std::string strWalletFileIn)
47 strWalletFile = strWalletFileIn;
50 pwalletdbEncryption = NULL;
53 std::map<uint256, CWalletTx> mapWallet;
54 std::vector<uint256> vWalletUpdated;
56 std::map<uint256, int> mapRequestCount;
58 std::map<CBitcoinAddress, std::string> mapAddressBook;
60 std::vector<unsigned char> vchDefaultKey;
62 // keystore implementation
63 // Adds a key to the store, and saves it to disk.
64 bool AddKey(const CKey& key);
65 // Adds a key to the store, without saving it to disk (used by LoadWallet)
66 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
68 // Adds an encrypted key to the store, and saves it to disk.
69 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
70 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
71 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
73 bool Unlock(const SecureString& strWalletPassphrase);
74 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
75 bool EncryptWallet(const SecureString& strWalletPassphrase);
77 bool AddToWallet(const CWalletTx& wtxIn);
78 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
79 bool EraseFromWallet(uint256 hash);
80 void WalletUpdateSpent(const CTransaction& prevout);
81 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
82 int ScanForWalletTransaction(const uint256& hashTx);
83 void ReacceptWalletTransactions();
84 void ResendWalletTransactions();
85 int64 GetBalance() const;
86 int64 GetUnconfirmedBalance() const;
87 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
88 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
89 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
90 bool BroadcastTransaction(CWalletTx& wtxNew);
91 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
92 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
96 int64 AddReserveKey(const CKeyPool& keypool);
97 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
98 void KeepKey(int64 nIndex);
99 void ReturnKey(int64 nIndex);
100 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
101 int64 GetOldestKeyPoolTime();
102 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
104 bool IsMine(const CTxIn& txin) const;
105 int64 GetDebit(const CTxIn& txin) const;
106 bool IsMine(const CTxOut& txout) const
108 return ::IsMine(*this, txout.scriptPubKey);
110 int64 GetCredit(const CTxOut& txout) const
112 if (!MoneyRange(txout.nValue))
113 throw std::runtime_error("CWallet::GetCredit() : value out of range");
114 return (IsMine(txout) ? txout.nValue : 0);
116 bool IsChange(const CTxOut& txout) const
118 CBitcoinAddress address;
119 if (ExtractAddress(txout.scriptPubKey, this, address))
120 CRITICAL_BLOCK(cs_wallet)
121 if (!mapAddressBook.count(address))
125 int64 GetChange(const CTxOut& txout) const
127 if (!MoneyRange(txout.nValue))
128 throw std::runtime_error("CWallet::GetChange() : value out of range");
129 return (IsChange(txout) ? txout.nValue : 0);
131 bool IsMine(const CTransaction& tx) const
133 BOOST_FOREACH(const CTxOut& txout, tx.vout)
138 bool IsFromMe(const CTransaction& tx) const
140 return (GetDebit(tx) > 0);
142 int64 GetDebit(const CTransaction& tx) const
145 BOOST_FOREACH(const CTxIn& txin, tx.vin)
147 nDebit += GetDebit(txin);
148 if (!MoneyRange(nDebit))
149 throw std::runtime_error("CWallet::GetDebit() : value out of range");
153 int64 GetCredit(const CTransaction& tx) const
156 BOOST_FOREACH(const CTxOut& txout, tx.vout)
158 nCredit += GetCredit(txout);
159 if (!MoneyRange(nCredit))
160 throw std::runtime_error("CWallet::GetCredit() : value out of range");
164 int64 GetChange(const CTransaction& tx) const
167 BOOST_FOREACH(const CTxOut& txout, tx.vout)
169 nChange += GetChange(txout);
170 if (!MoneyRange(nChange))
171 throw std::runtime_error("CWallet::GetChange() : value out of range");
175 void SetBestChain(const CBlockLocator& loc)
177 CWalletDB walletdb(strWalletFile);
178 walletdb.WriteBestBlock(loc);
181 int LoadWallet(bool& fFirstRunRet);
182 // bool BackupWallet(const std::string& strDest);
184 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
186 bool DelAddressBookName(const CBitcoinAddress& address);
188 void UpdatedTransaction(const uint256 &hashTx)
190 CRITICAL_BLOCK(cs_wallet)
191 vWalletUpdated.push_back(hashTx);
194 void PrintWallet(const CBlock& block);
196 void Inventory(const uint256 &hash)
198 CRITICAL_BLOCK(cs_wallet)
200 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
201 if (mi != mapRequestCount.end())
208 return setKeyPool.size();
211 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
213 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
222 std::vector<unsigned char> vchPubKey;
224 CReserveKey(CWallet* pwalletIn)
237 std::vector<unsigned char> GetReservedKey();
243 // A transaction with a bunch of additional info that only the owner cares
244 // about. It includes any unrecorded transactions needed to link it back
245 // to the block chain.
247 class CWalletTx : public CMerkleTx
250 const CWallet* pwallet;
253 std::vector<CMerkleTx> vtxPrev;
254 std::map<std::string, std::string> mapValue;
255 std::vector<std::pair<std::string, std::string> > vOrderForm;
256 unsigned int fTimeReceivedIsTxTime;
257 unsigned int nTimeReceived; // time received by this node
259 std::string strFromAccount;
260 std::vector<char> vfSpent; // which outputs are already spent
263 mutable char fDebitCached;
264 mutable char fCreditCached;
265 mutable char fAvailableCreditCached;
266 mutable char fChangeCached;
267 mutable int64 nDebitCached;
268 mutable int64 nCreditCached;
269 mutable int64 nAvailableCreditCached;
270 mutable int64 nChangeCached;
272 // memory only UI hints
273 mutable unsigned int nTimeDisplayed;
274 mutable int nLinesDisplayed;
275 mutable char fConfirmedDisplayed;
282 CWalletTx(const CWallet* pwalletIn)
287 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
292 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
297 void Init(const CWallet* pwalletIn)
303 fTimeReceivedIsTxTime = false;
306 strFromAccount.clear();
308 fDebitCached = false;
309 fCreditCached = false;
310 fAvailableCreditCached = false;
311 fChangeCached = false;
314 nAvailableCreditCached = 0;
318 fConfirmedDisplayed = false;
323 CWalletTx* pthis = const_cast<CWalletTx*>(this);
330 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
333 BOOST_FOREACH(char f, vfSpent)
335 str += (f ? '1' : '0');
339 pthis->mapValue["spent"] = str;
342 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
345 READWRITE(vOrderForm);
346 READWRITE(fTimeReceivedIsTxTime);
347 READWRITE(nTimeReceived);
353 pthis->strFromAccount = pthis->mapValue["fromaccount"];
355 if (mapValue.count("spent"))
356 BOOST_FOREACH(char c, pthis->mapValue["spent"])
357 pthis->vfSpent.push_back(c != '0');
359 pthis->vfSpent.assign(vout.size(), fSpent);
362 pthis->mapValue.erase("fromaccount");
363 pthis->mapValue.erase("version");
364 pthis->mapValue.erase("spent");
367 // marks certain txout's as spent
368 // returns true if any update took place
369 bool UpdateSpent(const std::vector<char>& vfNewSpent)
371 bool fReturn = false;
372 for (int i=0; i < vfNewSpent.size(); i++)
374 if (i == vfSpent.size())
377 if (vfNewSpent[i] && !vfSpent[i])
381 fAvailableCreditCached = false;
387 // make sure balances are recalculated
390 fCreditCached = false;
391 fAvailableCreditCached = false;
392 fDebitCached = false;
393 fChangeCached = false;
396 void BindWallet(CWallet *pwalletIn)
402 void MarkSpent(unsigned int nOut)
404 if (nOut >= vout.size())
405 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
406 vfSpent.resize(vout.size());
409 vfSpent[nOut] = true;
410 fAvailableCreditCached = false;
414 bool IsSpent(unsigned int nOut) const
416 if (nOut >= vout.size())
417 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
418 if (nOut >= vfSpent.size())
420 return (!!vfSpent[nOut]);
423 int64 GetDebit() const
429 nDebitCached = pwallet->GetDebit(*this);
434 int64 GetCredit(bool fUseCache=true) const
436 // Must wait until coinbase is safely deep enough in the chain before valuing it
437 if (IsCoinBase() && GetBlocksToMaturity() > 0)
440 // GetBalance can assume transactions in mapWallet won't change
441 if (fUseCache && fCreditCached)
442 return nCreditCached;
443 nCreditCached = pwallet->GetCredit(*this);
444 fCreditCached = true;
445 return nCreditCached;
448 int64 GetAvailableCredit(bool fUseCache=true) const
450 // Must wait until coinbase is safely deep enough in the chain before valuing it
451 if (IsCoinBase() && GetBlocksToMaturity() > 0)
454 if (fUseCache && fAvailableCreditCached)
455 return nAvailableCreditCached;
458 for (int i = 0; i < vout.size(); i++)
462 const CTxOut &txout = vout[i];
463 nCredit += pwallet->GetCredit(txout);
464 if (!MoneyRange(nCredit))
465 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
469 nAvailableCreditCached = nCredit;
470 fAvailableCreditCached = true;
475 int64 GetChange() const
478 return nChangeCached;
479 nChangeCached = pwallet->GetChange(*this);
480 fChangeCached = true;
481 return nChangeCached;
484 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
485 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
487 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
488 int64& nSent, int64& nFee) const;
490 bool IsFromMe() const
492 return (GetDebit() > 0);
495 bool IsConfirmed() const
497 // Quick answer in most cases
500 if (GetDepthInMainChain() >= 1)
502 if (!IsFromMe()) // using wtx's cached debit
505 // If no confirmations but it's from us, we can still
506 // consider it confirmed if all dependencies are confirmed
507 std::map<uint256, const CMerkleTx*> mapPrev;
508 std::vector<const CMerkleTx*> vWorkQueue;
509 vWorkQueue.reserve(vtxPrev.size()+1);
510 vWorkQueue.push_back(this);
511 for (int i = 0; i < vWorkQueue.size(); i++)
513 const CMerkleTx* ptx = vWorkQueue[i];
517 if (ptx->GetDepthInMainChain() >= 1)
519 if (!pwallet->IsFromMe(*ptx))
523 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
524 mapPrev[tx.GetHash()] = &tx;
526 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
528 if (!mapPrev.count(txin.prevout.hash))
530 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
538 int64 GetTxTime() const;
539 int GetRequestCount() const;
541 void AddSupportingTransactions(CTxDB& txdb);
543 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
544 bool AcceptWalletTransaction();
546 void RelayWalletTransaction(CTxDB& txdb);
547 void RelayWalletTransaction();
552 // Private key that includes an expiration date in case it never gets used.
560 std::string strComment;
561 //// todo: add something to note what created it (user, getnewaddress, change)
562 //// maybe should have a map<string, string> property map
564 CWalletKey(int64 nExpires=0)
566 nTimeCreated = (nExpires ? GetTime() : 0);
567 nTimeExpires = nExpires;
572 if (!(nType & SER_GETHASH))
574 READWRITE(vchPrivKey);
575 READWRITE(nTimeCreated);
576 READWRITE(nTimeExpires);
577 READWRITE(strComment);
587 // Account information.
588 // Stored in wallet with key "acc"+string account name
593 std::vector<unsigned char> vchPubKey;
607 if (!(nType & SER_GETHASH))
609 READWRITE(vchPubKey);
616 // Internal transfers.
617 // Database key is acentry<account><counter>
619 class CAccountingEntry
622 std::string strAccount;
625 std::string strOtherAccount;
626 std::string strComment;
638 strOtherAccount.clear();
644 if (!(nType & SER_GETHASH))
646 // Note: strAccount is serialized as part of the key, not here.
647 READWRITE(nCreditDebit);
649 READWRITE(strOtherAccount);
650 READWRITE(strComment);
654 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);