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 COPYING 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);
79 bool EraseFromWallet(uint256 hash);
80 void WalletUpdateSpent(const CTransaction& prevout);
81 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
82 void ReacceptWalletTransactions();
83 void ResendWalletTransactions();
84 int64 GetBalance() const;
85 int64 GetUnconfirmedBalance() const;
86 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
87 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
88 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
89 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
90 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
94 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
95 void KeepKey(int64 nIndex);
96 void ReturnKey(int64 nIndex);
97 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
98 int64 GetOldestKeyPoolTime();
100 bool IsMine(const CTxIn& txin) const;
101 int64 GetDebit(const CTxIn& txin) const;
102 bool IsMine(const CTxOut& txout) const
104 return ::IsMine(*this, txout.scriptPubKey);
106 int64 GetCredit(const CTxOut& txout) const
108 if (!MoneyRange(txout.nValue))
109 throw std::runtime_error("CWallet::GetCredit() : value out of range");
110 return (IsMine(txout) ? txout.nValue : 0);
112 bool IsChange(const CTxOut& txout) const
114 CBitcoinAddress address;
115 if (ExtractAddress(txout.scriptPubKey, this, address))
116 CRITICAL_BLOCK(cs_wallet)
117 if (!mapAddressBook.count(address))
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);
179 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
181 bool DelAddressBookName(const CBitcoinAddress& address);
183 void UpdatedTransaction(const uint256 &hashTx)
185 CRITICAL_BLOCK(cs_wallet)
186 vWalletUpdated.push_back(hashTx);
189 void PrintWallet(const CBlock& block);
191 void Inventory(const uint256 &hash)
193 CRITICAL_BLOCK(cs_wallet)
195 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
196 if (mi != mapRequestCount.end())
203 return setKeyPool.size();
206 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
208 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
217 std::vector<unsigned char> vchPubKey;
219 CReserveKey(CWallet* pwalletIn)
232 std::vector<unsigned char> GetReservedKey();
238 // A transaction with a bunch of additional info that only the owner cares
239 // about. It includes any unrecorded transactions needed to link it back
240 // to the block chain.
242 class CWalletTx : public CMerkleTx
245 const CWallet* pwallet;
247 std::vector<CMerkleTx> vtxPrev;
248 std::map<std::string, std::string> mapValue;
249 std::vector<std::pair<std::string, std::string> > vOrderForm;
250 unsigned int fTimeReceivedIsTxTime;
251 unsigned int nTimeReceived; // time received by this node
253 std::string strFromAccount;
254 std::vector<char> vfSpent; // which outputs are already spent
257 mutable char fDebitCached;
258 mutable char fCreditCached;
259 mutable char fAvailableCreditCached;
260 mutable char fChangeCached;
261 mutable int64 nDebitCached;
262 mutable int64 nCreditCached;
263 mutable int64 nAvailableCreditCached;
264 mutable int64 nChangeCached;
266 // memory only UI hints
267 mutable unsigned int nTimeDisplayed;
268 mutable int nLinesDisplayed;
269 mutable char fConfirmedDisplayed;
276 CWalletTx(const CWallet* pwalletIn)
281 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
286 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
291 void Init(const CWallet* pwalletIn)
297 fTimeReceivedIsTxTime = false;
300 strFromAccount.clear();
302 fDebitCached = false;
303 fCreditCached = false;
304 fAvailableCreditCached = false;
305 fChangeCached = false;
308 nAvailableCreditCached = 0;
312 fConfirmedDisplayed = false;
317 CWalletTx* pthis = const_cast<CWalletTx*>(this);
324 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
327 BOOST_FOREACH(char f, vfSpent)
329 str += (f ? '1' : '0');
333 pthis->mapValue["spent"] = str;
336 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
339 READWRITE(vOrderForm);
340 READWRITE(fTimeReceivedIsTxTime);
341 READWRITE(nTimeReceived);
347 pthis->strFromAccount = pthis->mapValue["fromaccount"];
349 if (mapValue.count("spent"))
350 BOOST_FOREACH(char c, pthis->mapValue["spent"])
351 pthis->vfSpent.push_back(c != '0');
353 pthis->vfSpent.assign(vout.size(), fSpent);
356 pthis->mapValue.erase("fromaccount");
357 pthis->mapValue.erase("version");
358 pthis->mapValue.erase("spent");
361 // marks certain txout's as spent
362 // returns true if any update took place
363 bool UpdateSpent(const std::vector<char>& vfNewSpent)
365 bool fReturn = false;
366 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
368 if (i == vfSpent.size())
371 if (vfNewSpent[i] && !vfSpent[i])
375 fAvailableCreditCached = false;
381 // make sure balances are recalculated
384 fCreditCached = false;
385 fAvailableCreditCached = false;
386 fDebitCached = false;
387 fChangeCached = false;
390 void MarkSpent(unsigned int nOut)
392 if (nOut >= vout.size())
393 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
394 vfSpent.resize(vout.size());
397 vfSpent[nOut] = true;
398 fAvailableCreditCached = false;
402 bool IsSpent(unsigned int nOut) const
404 if (nOut >= vout.size())
405 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
406 if (nOut >= vfSpent.size())
408 return (!!vfSpent[nOut]);
411 int64 GetDebit() const
417 nDebitCached = pwallet->GetDebit(*this);
422 int64 GetCredit(bool fUseCache=true) const
424 // Must wait until coinbase is safely deep enough in the chain before valuing it
425 if (IsCoinBase() && GetBlocksToMaturity() > 0)
428 // GetBalance can assume transactions in mapWallet won't change
429 if (fUseCache && fCreditCached)
430 return nCreditCached;
431 nCreditCached = pwallet->GetCredit(*this);
432 fCreditCached = true;
433 return nCreditCached;
436 int64 GetAvailableCredit(bool fUseCache=true) const
438 // Must wait until coinbase is safely deep enough in the chain before valuing it
439 if (IsCoinBase() && GetBlocksToMaturity() > 0)
442 if (fUseCache && fAvailableCreditCached)
443 return nAvailableCreditCached;
446 for (unsigned int i = 0; i < vout.size(); i++)
450 const CTxOut &txout = vout[i];
451 nCredit += pwallet->GetCredit(txout);
452 if (!MoneyRange(nCredit))
453 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
457 nAvailableCreditCached = nCredit;
458 fAvailableCreditCached = true;
463 int64 GetChange() const
466 return nChangeCached;
467 nChangeCached = pwallet->GetChange(*this);
468 fChangeCached = true;
469 return nChangeCached;
472 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
473 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
475 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
476 int64& nSent, int64& nFee) const;
478 bool IsFromMe() const
480 return (GetDebit() > 0);
483 bool IsConfirmed() const
485 // Quick answer in most cases
488 if (GetDepthInMainChain() >= 1)
490 if (!IsFromMe()) // using wtx's cached debit
493 // If no confirmations but it's from us, we can still
494 // consider it confirmed if all dependencies are confirmed
495 std::map<uint256, const CMerkleTx*> mapPrev;
496 std::vector<const CMerkleTx*> vWorkQueue;
497 vWorkQueue.reserve(vtxPrev.size()+1);
498 vWorkQueue.push_back(this);
499 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
501 const CMerkleTx* ptx = vWorkQueue[i];
505 if (ptx->GetDepthInMainChain() >= 1)
507 if (!pwallet->IsFromMe(*ptx))
512 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
513 mapPrev[tx.GetHash()] = &tx;
516 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
518 if (!mapPrev.count(txin.prevout.hash))
520 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
528 int64 GetTxTime() const;
529 int GetRequestCount() const;
531 void AddSupportingTransactions(CTxDB& txdb);
533 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
534 bool AcceptWalletTransaction();
536 void RelayWalletTransaction(CTxDB& txdb);
537 void RelayWalletTransaction();
542 // Private key that includes an expiration date in case it never gets used.
550 std::string strComment;
551 //// todo: add something to note what created it (user, getnewaddress, change)
552 //// maybe should have a map<string, string> property map
554 CWalletKey(int64 nExpires=0)
556 nTimeCreated = (nExpires ? GetTime() : 0);
557 nTimeExpires = nExpires;
562 if (!(nType & SER_GETHASH))
564 READWRITE(vchPrivKey);
565 READWRITE(nTimeCreated);
566 READWRITE(nTimeExpires);
567 READWRITE(strComment);
577 // Account information.
578 // Stored in wallet with key "acc"+string account name
583 std::vector<unsigned char> vchPubKey;
597 if (!(nType & SER_GETHASH))
599 READWRITE(vchPubKey);
606 // Internal transfers.
607 // Database key is acentry<account><counter>
609 class CAccountingEntry
612 std::string strAccount;
615 std::string strOtherAccount;
616 std::string strComment;
628 strOtherAccount.clear();
634 if (!(nType & SER_GETHASH))
636 // Note: strAccount is serialized as part of the key, not here.
637 READWRITE(nCreditDebit);
639 READWRITE(strOtherAccount);
640 READWRITE(strComment);
644 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);