1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_WALLET_H
7 #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, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
24 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, 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); }
74 bool Unlock(const SecureString& strWalletPassphrase);
75 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
76 bool EncryptWallet(const SecureString& strWalletPassphrase);
78 bool AddToWallet(const CWalletTx& wtxIn);
79 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
80 bool EraseFromWallet(uint256 hash);
81 void WalletUpdateSpent(const CTransaction& prevout);
82 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
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 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
97 void KeepKey(int64 nIndex);
98 void ReturnKey(int64 nIndex);
99 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
100 int64 GetOldestKeyPoolTime();
102 bool IsMine(const CTxIn& txin) const;
103 int64 GetDebit(const CTxIn& txin) const;
104 bool IsMine(const CTxOut& txout) const
106 return ::IsMine(*this, txout.scriptPubKey);
108 int64 GetCredit(const CTxOut& txout) const
110 if (!MoneyRange(txout.nValue))
111 throw std::runtime_error("CWallet::GetCredit() : value out of range");
112 return (IsMine(txout) ? txout.nValue : 0);
114 bool IsChange(const CTxOut& txout) const
116 CBitcoinAddress address;
117 if (ExtractAddress(txout.scriptPubKey, this, address))
118 CRITICAL_BLOCK(cs_wallet)
119 if (!mapAddressBook.count(address))
123 int64 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 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 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 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;
250 std::vector<CMerkleTx> vtxPrev;
251 std::map<std::string, std::string> mapValue;
252 std::vector<std::pair<std::string, std::string> > vOrderForm;
253 unsigned int fTimeReceivedIsTxTime;
254 unsigned int nTimeReceived; // time received by this node
256 std::string strFromAccount;
257 std::vector<char> vfSpent; // which outputs are already spent
260 mutable char fDebitCached;
261 mutable char fCreditCached;
262 mutable char fAvailableCreditCached;
263 mutable char fChangeCached;
264 mutable int64 nDebitCached;
265 mutable int64 nCreditCached;
266 mutable int64 nAvailableCreditCached;
267 mutable int64 nChangeCached;
269 // memory only UI hints
270 mutable unsigned int nTimeDisplayed;
271 mutable int nLinesDisplayed;
272 mutable char fConfirmedDisplayed;
279 CWalletTx(const CWallet* pwalletIn)
284 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
289 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
294 void Init(const CWallet* pwalletIn)
300 fTimeReceivedIsTxTime = false;
303 strFromAccount.clear();
305 fDebitCached = false;
306 fCreditCached = false;
307 fAvailableCreditCached = false;
308 fChangeCached = false;
311 nAvailableCreditCached = 0;
315 fConfirmedDisplayed = false;
320 CWalletTx* pthis = const_cast<CWalletTx*>(this);
327 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
330 BOOST_FOREACH(char f, vfSpent)
332 str += (f ? '1' : '0');
336 pthis->mapValue["spent"] = str;
339 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
342 READWRITE(vOrderForm);
343 READWRITE(fTimeReceivedIsTxTime);
344 READWRITE(nTimeReceived);
350 pthis->strFromAccount = pthis->mapValue["fromaccount"];
352 if (mapValue.count("spent"))
353 BOOST_FOREACH(char c, pthis->mapValue["spent"])
354 pthis->vfSpent.push_back(c != '0');
356 pthis->vfSpent.assign(vout.size(), fSpent);
359 pthis->mapValue.erase("fromaccount");
360 pthis->mapValue.erase("version");
361 pthis->mapValue.erase("spent");
364 // marks certain txout's as spent
365 // returns true if any update took place
366 bool UpdateSpent(const std::vector<char>& vfNewSpent)
368 bool fReturn = false;
369 for (int i=0; i < vfNewSpent.size(); i++)
371 if (i == vfSpent.size())
374 if (vfNewSpent[i] && !vfSpent[i])
378 fAvailableCreditCached = false;
384 // make sure balances are recalculated
387 fCreditCached = false;
388 fAvailableCreditCached = false;
389 fDebitCached = false;
390 fChangeCached = false;
393 void MarkSpent(unsigned int nOut)
395 if (nOut >= vout.size())
396 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
397 vfSpent.resize(vout.size());
400 vfSpent[nOut] = true;
401 fAvailableCreditCached = false;
405 bool IsSpent(unsigned int nOut) const
407 if (nOut >= vout.size())
408 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
409 if (nOut >= vfSpent.size())
411 return (!!vfSpent[nOut]);
414 int64 GetDebit() const
420 nDebitCached = pwallet->GetDebit(*this);
425 int64 GetCredit(bool fUseCache=true) const
427 // Must wait until coinbase is safely deep enough in the chain before valuing it
428 if (IsCoinBase() && GetBlocksToMaturity() > 0)
431 // GetBalance can assume transactions in mapWallet won't change
432 if (fUseCache && fCreditCached)
433 return nCreditCached;
434 nCreditCached = pwallet->GetCredit(*this);
435 fCreditCached = true;
436 return nCreditCached;
439 int64 GetAvailableCredit(bool fUseCache=true) const
441 // Must wait until coinbase is safely deep enough in the chain before valuing it
442 if (IsCoinBase() && GetBlocksToMaturity() > 0)
445 if (fUseCache && fAvailableCreditCached)
446 return nAvailableCreditCached;
449 for (int i = 0; i < vout.size(); i++)
453 const CTxOut &txout = vout[i];
454 nCredit += pwallet->GetCredit(txout);
455 if (!MoneyRange(nCredit))
456 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
460 nAvailableCreditCached = nCredit;
461 fAvailableCreditCached = true;
466 int64 GetChange() const
469 return nChangeCached;
470 nChangeCached = pwallet->GetChange(*this);
471 fChangeCached = true;
472 return nChangeCached;
475 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
476 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
478 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
479 int64& nSent, int64& nFee) const;
481 bool IsFromMe() const
483 return (GetDebit() > 0);
486 bool IsConfirmed() const
488 // Quick answer in most cases
491 if (GetDepthInMainChain() >= 1)
493 if (!IsFromMe()) // using wtx's cached debit
496 // If no confirmations but it's from us, we can still
497 // consider it confirmed if all dependencies are confirmed
498 std::map<uint256, const CMerkleTx*> mapPrev;
499 std::vector<const CMerkleTx*> vWorkQueue;
500 vWorkQueue.reserve(vtxPrev.size()+1);
501 vWorkQueue.push_back(this);
502 for (int i = 0; i < vWorkQueue.size(); i++)
504 const CMerkleTx* ptx = vWorkQueue[i];
508 if (ptx->GetDepthInMainChain() >= 1)
510 if (!pwallet->IsFromMe(*ptx))
514 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
515 mapPrev[tx.GetHash()] = &tx;
517 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
519 if (!mapPrev.count(txin.prevout.hash))
521 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
529 int64 GetTxTime() const;
530 int GetRequestCount() const;
532 void AddSupportingTransactions(CTxDB& txdb);
534 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
535 bool AcceptWalletTransaction();
537 void RelayWalletTransaction(CTxDB& txdb);
538 void RelayWalletTransaction();
543 // Private key that includes an expiration date in case it never gets used.
551 std::string strComment;
552 //// todo: add something to note what created it (user, getnewaddress, change)
553 //// maybe should have a map<string, string> property map
555 CWalletKey(int64 nExpires=0)
557 nTimeCreated = (nExpires ? GetTime() : 0);
558 nTimeExpires = nExpires;
563 if (!(nType & SER_GETHASH))
565 READWRITE(vchPrivKey);
566 READWRITE(nTimeCreated);
567 READWRITE(nTimeExpires);
568 READWRITE(strComment);
578 // Account information.
579 // Stored in wallet with key "acc"+string account name
584 std::vector<unsigned char> vchPubKey;
598 if (!(nType & SER_GETHASH))
600 READWRITE(vchPubKey);
607 // Internal transfers.
608 // Database key is acentry<account><counter>
610 class CAccountingEntry
613 std::string strAccount;
616 std::string strOtherAccount;
617 std::string strComment;
629 strOtherAccount.clear();
635 if (!(nType & SER_GETHASH))
637 // Note: strAccount is serialized as part of the key, not here.
638 READWRITE(nCreditDebit);
640 READWRITE(strOtherAccount);
641 READWRITE(strComment);
645 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);