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 int64 GetStake() const;
88 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
89 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
90 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
91 bool BroadcastTransaction(CWalletTx& wtxNew);
92 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
93 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
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();
103 bool IsMine(const CTxIn& txin) const;
104 int64 GetDebit(const CTxIn& txin) const;
105 bool IsMine(const CTxOut& txout) const
107 return ::IsMine(*this, txout.scriptPubKey);
109 int64 GetCredit(const CTxOut& txout) const
111 if (!MoneyRange(txout.nValue))
112 throw std::runtime_error("CWallet::GetCredit() : value out of range");
113 return (IsMine(txout) ? txout.nValue : 0);
115 bool IsChange(const CTxOut& txout) const
117 CBitcoinAddress address;
118 if (ExtractAddress(txout.scriptPubKey, this, address))
119 CRITICAL_BLOCK(cs_wallet)
120 if (!mapAddressBook.count(address))
124 int64 GetChange(const CTxOut& txout) const
126 if (!MoneyRange(txout.nValue))
127 throw std::runtime_error("CWallet::GetChange() : value out of range");
128 return (IsChange(txout) ? txout.nValue : 0);
130 bool IsMine(const CTransaction& tx) const
132 BOOST_FOREACH(const CTxOut& txout, tx.vout)
137 bool IsFromMe(const CTransaction& tx) const
139 return (GetDebit(tx) > 0);
141 int64 GetDebit(const CTransaction& tx) const
144 BOOST_FOREACH(const CTxIn& txin, tx.vin)
146 nDebit += GetDebit(txin);
147 if (!MoneyRange(nDebit))
148 throw std::runtime_error("CWallet::GetDebit() : value out of range");
152 int64 GetCredit(const CTransaction& tx) const
155 BOOST_FOREACH(const CTxOut& txout, tx.vout)
157 nCredit += GetCredit(txout);
158 if (!MoneyRange(nCredit))
159 throw std::runtime_error("CWallet::GetCredit() : value out of range");
163 int64 GetChange(const CTransaction& tx) const
166 BOOST_FOREACH(const CTxOut& txout, tx.vout)
168 nChange += GetChange(txout);
169 if (!MoneyRange(nChange))
170 throw std::runtime_error("CWallet::GetChange() : value out of range");
174 void SetBestChain(const CBlockLocator& loc)
176 CWalletDB walletdb(strWalletFile);
177 walletdb.WriteBestBlock(loc);
180 int LoadWallet(bool& fFirstRunRet);
181 // bool BackupWallet(const std::string& strDest);
183 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
185 bool DelAddressBookName(const CBitcoinAddress& address);
187 void UpdatedTransaction(const uint256 &hashTx)
189 CRITICAL_BLOCK(cs_wallet)
190 vWalletUpdated.push_back(hashTx);
193 void PrintWallet(const CBlock& block);
195 void Inventory(const uint256 &hash)
197 CRITICAL_BLOCK(cs_wallet)
199 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
200 if (mi != mapRequestCount.end())
207 return setKeyPool.size();
210 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
212 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
221 std::vector<unsigned char> vchPubKey;
223 CReserveKey(CWallet* pwalletIn)
236 std::vector<unsigned char> GetReservedKey();
242 // A transaction with a bunch of additional info that only the owner cares
243 // about. It includes any unrecorded transactions needed to link it back
244 // to the block chain.
246 class CWalletTx : public CMerkleTx
249 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 nDebitCached;
266 mutable int64 nCreditCached;
267 mutable int64 nAvailableCreditCached;
268 mutable int64 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 MarkSpent(unsigned int nOut)
396 if (nOut >= vout.size())
397 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
398 vfSpent.resize(vout.size());
401 vfSpent[nOut] = true;
402 fAvailableCreditCached = false;
406 bool IsSpent(unsigned int nOut) const
408 if (nOut >= vout.size())
409 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
410 if (nOut >= vfSpent.size())
412 return (!!vfSpent[nOut]);
415 int64 GetDebit() const
421 nDebitCached = pwallet->GetDebit(*this);
426 int64 GetCredit(bool fUseCache=true) const
428 // Must wait until coinbase is safely deep enough in the chain before valuing it
429 if (IsCoinBase() && GetBlocksToMaturity() > 0)
432 // GetBalance can assume transactions in mapWallet won't change
433 if (fUseCache && fCreditCached)
434 return nCreditCached;
435 nCreditCached = pwallet->GetCredit(*this);
436 fCreditCached = true;
437 return nCreditCached;
440 int64 GetAvailableCredit(bool fUseCache=true) const
442 // Must wait until coinbase is safely deep enough in the chain before valuing it
443 if (IsCoinBase() && GetBlocksToMaturity() > 0)
446 if (fUseCache && fAvailableCreditCached)
447 return nAvailableCreditCached;
450 for (int i = 0; i < vout.size(); i++)
454 const CTxOut &txout = vout[i];
455 nCredit += pwallet->GetCredit(txout);
456 if (!MoneyRange(nCredit))
457 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
461 nAvailableCreditCached = nCredit;
462 fAvailableCreditCached = true;
467 int64 GetChange() const
470 return nChangeCached;
471 nChangeCached = pwallet->GetChange(*this);
472 fChangeCached = true;
473 return nChangeCached;
476 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
477 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
479 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
480 int64& nSent, int64& nFee) const;
482 bool IsFromMe() const
484 return (GetDebit() > 0);
487 bool IsConfirmed() const
489 // Quick answer in most cases
492 if (GetDepthInMainChain() >= 1)
494 if (!IsFromMe()) // using wtx's cached debit
497 // If no confirmations but it's from us, we can still
498 // consider it confirmed if all dependencies are confirmed
499 std::map<uint256, const CMerkleTx*> mapPrev;
500 std::vector<const CMerkleTx*> vWorkQueue;
501 vWorkQueue.reserve(vtxPrev.size()+1);
502 vWorkQueue.push_back(this);
503 for (int i = 0; i < vWorkQueue.size(); i++)
505 const CMerkleTx* ptx = vWorkQueue[i];
509 if (ptx->GetDepthInMainChain() >= 1)
511 if (!pwallet->IsFromMe(*ptx))
515 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
516 mapPrev[tx.GetHash()] = &tx;
518 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
520 if (!mapPrev.count(txin.prevout.hash))
522 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
530 int64 GetTxTime() const;
531 int GetRequestCount() const;
533 void AddSupportingTransactions(CTxDB& txdb);
535 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
536 bool AcceptWalletTransaction();
538 void RelayWalletTransaction(CTxDB& txdb);
539 void RelayWalletTransaction();
544 // Private key that includes an expiration date in case it never gets used.
552 std::string strComment;
553 //// todo: add something to note what created it (user, getnewaddress, change)
554 //// maybe should have a map<string, string> property map
556 CWalletKey(int64 nExpires=0)
558 nTimeCreated = (nExpires ? GetTime() : 0);
559 nTimeExpires = nExpires;
564 if (!(nType & SER_GETHASH))
566 READWRITE(vchPrivKey);
567 READWRITE(nTimeCreated);
568 READWRITE(nTimeExpires);
569 READWRITE(strComment);
579 // Account information.
580 // Stored in wallet with key "acc"+string account name
585 std::vector<unsigned char> vchPubKey;
599 if (!(nType & SER_GETHASH))
601 READWRITE(vchPubKey);
608 // Internal transfers.
609 // Database key is acentry<account><counter>
611 class CAccountingEntry
614 std::string strAccount;
617 std::string strOtherAccount;
618 std::string strComment;
630 strOtherAccount.clear();
636 if (!(nType & SER_GETHASH))
638 // Note: strAccount is serialized as part of the key, not here.
639 READWRITE(nCreditDebit);
641 READWRITE(strOtherAccount);
642 READWRITE(strComment);
646 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);