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 class CWallet : public CCryptoKeyStore
19 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
20 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
22 CWalletDB *pwalletdbEncryption;
23 CCriticalSection cs_pwalletdbEncryption;
27 std::string strWalletFile;
29 std::set<int64> setKeyPool;
30 CCriticalSection cs_setKeyPool;
32 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
33 MasterKeyMap mapMasterKeys;
34 unsigned int nMasterKeyMaxID;
40 pwalletdbEncryption = NULL;
42 CWallet(std::string strWalletFileIn)
44 strWalletFile = strWalletFileIn;
47 pwalletdbEncryption = NULL;
50 mutable CCriticalSection cs_mapWallet;
51 std::map<uint256, CWalletTx> mapWallet;
52 std::vector<uint256> vWalletUpdated;
54 std::map<uint256, int> mapRequestCount;
55 mutable CCriticalSection cs_mapRequestCount;
57 std::map<CBitcoinAddress, std::string> mapAddressBook;
58 mutable CCriticalSection cs_mapAddressBook;
60 std::vector<unsigned char> vchDefaultKey;
62 // keystore implementation
63 bool AddKey(const CKey& key);
64 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
65 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
66 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
68 bool Unlock(const std::string& strWalletPassphrase);
69 bool ChangeWalletPassphrase(const std::string& strOldWalletPassphrase, const std::string& strNewWalletPassphrase);
70 bool EncryptWallet(const std::string& strWalletPassphrase);
72 bool AddToWallet(const CWalletTx& wtxIn);
73 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
74 bool EraseFromWallet(uint256 hash);
75 void WalletUpdateSpent(const CTransaction& prevout);
76 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
77 void ReacceptWalletTransactions();
78 void ResendWalletTransactions();
79 int64 GetBalance() const;
80 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
81 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
82 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
83 bool BroadcastTransaction(CWalletTx& wtxNew);
84 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
85 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
88 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
89 void KeepKey(int64 nIndex);
90 void ReturnKey(int64 nIndex);
91 std::vector<unsigned char> GetOrReuseKeyFromPool();
92 int64 GetOldestKeyPoolTime();
94 bool IsMine(const CTxIn& txin) const;
95 int64 GetDebit(const CTxIn& txin) const;
96 bool IsMine(const CTxOut& txout) const
98 return ::IsMine(*this, txout.scriptPubKey);
100 int64 GetCredit(const CTxOut& txout) const
102 if (!MoneyRange(txout.nValue))
103 throw std::runtime_error("CWallet::GetCredit() : value out of range");
104 return (IsMine(txout) ? txout.nValue : 0);
106 bool IsChange(const CTxOut& txout) const
108 CBitcoinAddress address;
109 if (ExtractAddress(txout.scriptPubKey, this, address))
110 CRITICAL_BLOCK(cs_mapAddressBook)
111 if (!mapAddressBook.count(address))
115 int64 GetChange(const CTxOut& txout) const
117 if (!MoneyRange(txout.nValue))
118 throw std::runtime_error("CWallet::GetChange() : value out of range");
119 return (IsChange(txout) ? txout.nValue : 0);
121 bool IsMine(const CTransaction& tx) const
123 BOOST_FOREACH(const CTxOut& txout, tx.vout)
128 bool IsFromMe(const CTransaction& tx) const
130 return (GetDebit(tx) > 0);
132 int64 GetDebit(const CTransaction& tx) const
135 BOOST_FOREACH(const CTxIn& txin, tx.vin)
137 nDebit += GetDebit(txin);
138 if (!MoneyRange(nDebit))
139 throw std::runtime_error("CWallet::GetDebit() : value out of range");
143 int64 GetCredit(const CTransaction& tx) const
146 BOOST_FOREACH(const CTxOut& txout, tx.vout)
148 nCredit += GetCredit(txout);
149 if (!MoneyRange(nCredit))
150 throw std::runtime_error("CWallet::GetCredit() : value out of range");
154 int64 GetChange(const CTransaction& tx) const
157 BOOST_FOREACH(const CTxOut& txout, tx.vout)
159 nChange += GetChange(txout);
160 if (!MoneyRange(nChange))
161 throw std::runtime_error("CWallet::GetChange() : value out of range");
165 void SetBestChain(const CBlockLocator& loc)
167 CWalletDB walletdb(strWalletFile);
168 walletdb.WriteBestBlock(loc);
171 int LoadWallet(bool& fFirstRunRet);
172 // bool BackupWallet(const std::string& strDest);
174 // requires cs_mapAddressBook lock
175 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
177 // requires cs_mapAddressBook lock
178 bool DelAddressBookName(const CBitcoinAddress& address);
180 void UpdatedTransaction(const uint256 &hashTx)
182 CRITICAL_BLOCK(cs_mapWallet)
183 vWalletUpdated.push_back(hashTx);
186 void PrintWallet(const CBlock& block);
188 void Inventory(const uint256 &hash)
190 CRITICAL_BLOCK(cs_mapRequestCount)
192 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
193 if (mi != mapRequestCount.end())
200 return setKeyPool.size();
203 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
205 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
214 std::vector<unsigned char> vchPubKey;
216 CReserveKey(CWallet* pwalletIn)
229 std::vector<unsigned char> GetReservedKey();
235 // A transaction with a bunch of additional info that only the owner cares
236 // about. It includes any unrecorded transactions needed to link it back
237 // to the block chain.
239 class CWalletTx : public CMerkleTx
242 const CWallet* pwallet;
244 std::vector<CMerkleTx> vtxPrev;
245 std::map<std::string, std::string> mapValue;
246 std::vector<std::pair<std::string, std::string> > vOrderForm;
247 unsigned int fTimeReceivedIsTxTime;
248 unsigned int nTimeReceived; // time received by this node
250 std::string strFromAccount;
251 std::vector<char> vfSpent;
254 mutable char fDebitCached;
255 mutable char fCreditCached;
256 mutable char fAvailableCreditCached;
257 mutable char fChangeCached;
258 mutable int64 nDebitCached;
259 mutable int64 nCreditCached;
260 mutable int64 nAvailableCreditCached;
261 mutable int64 nChangeCached;
263 // memory only UI hints
264 mutable unsigned int nTimeDisplayed;
265 mutable int nLinesDisplayed;
266 mutable char fConfirmedDisplayed;
273 CWalletTx(const CWallet* pwalletIn)
278 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
283 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
288 void Init(const CWallet* pwalletIn)
294 fTimeReceivedIsTxTime = false;
297 strFromAccount.clear();
299 fDebitCached = false;
300 fCreditCached = false;
301 fAvailableCreditCached = false;
302 fChangeCached = false;
305 nAvailableCreditCached = 0;
309 fConfirmedDisplayed = false;
314 CWalletTx* pthis = const_cast<CWalletTx*>(this);
321 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
324 BOOST_FOREACH(char f, vfSpent)
326 str += (f ? '1' : '0');
330 pthis->mapValue["spent"] = str;
333 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
336 READWRITE(vOrderForm);
337 READWRITE(fTimeReceivedIsTxTime);
338 READWRITE(nTimeReceived);
344 pthis->strFromAccount = pthis->mapValue["fromaccount"];
346 if (mapValue.count("spent"))
347 BOOST_FOREACH(char c, pthis->mapValue["spent"])
348 pthis->vfSpent.push_back(c != '0');
350 pthis->vfSpent.assign(vout.size(), fSpent);
353 pthis->mapValue.erase("fromaccount");
354 pthis->mapValue.erase("version");
355 pthis->mapValue.erase("spent");
358 // marks certain txout's as spent
359 // returns true if any update took place
360 bool UpdateSpent(const std::vector<char>& vfNewSpent)
362 bool fReturn = false;
363 for (int i=0; i < vfNewSpent.size(); i++)
365 if (i == vfSpent.size())
368 if (vfNewSpent[i] && !vfSpent[i])
372 fAvailableCreditCached = false;
380 fCreditCached = false;
381 fAvailableCreditCached = false;
382 fDebitCached = false;
383 fChangeCached = false;
386 void MarkSpent(unsigned int nOut)
388 if (nOut >= vout.size())
389 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
390 vfSpent.resize(vout.size());
393 vfSpent[nOut] = true;
394 fAvailableCreditCached = false;
398 bool IsSpent(unsigned int nOut) const
400 if (nOut >= vout.size())
401 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
402 if (nOut >= vfSpent.size())
404 return (!!vfSpent[nOut]);
407 int64 GetDebit() const
413 nDebitCached = pwallet->GetDebit(*this);
418 int64 GetCredit(bool fUseCache=true) const
420 // Must wait until coinbase is safely deep enough in the chain before valuing it
421 if (IsCoinBase() && GetBlocksToMaturity() > 0)
424 // GetBalance can assume transactions in mapWallet won't change
425 if (fUseCache && fCreditCached)
426 return nCreditCached;
427 nCreditCached = pwallet->GetCredit(*this);
428 fCreditCached = true;
429 return nCreditCached;
432 int64 GetAvailableCredit(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 if (fUseCache && fAvailableCreditCached)
439 return nAvailableCreditCached;
442 for (int i = 0; i < vout.size(); i++)
446 const CTxOut &txout = vout[i];
447 nCredit += pwallet->GetCredit(txout);
448 if (!MoneyRange(nCredit))
449 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
453 nAvailableCreditCached = nCredit;
454 fAvailableCreditCached = true;
459 int64 GetChange() const
462 return nChangeCached;
463 nChangeCached = pwallet->GetChange(*this);
464 fChangeCached = true;
465 return nChangeCached;
468 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
469 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
471 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
472 int64& nSent, int64& nFee) const;
474 bool IsFromMe() const
476 return (GetDebit() > 0);
479 bool IsConfirmed() const
481 // Quick answer in most cases
484 if (GetDepthInMainChain() >= 1)
486 if (!IsFromMe()) // using wtx's cached debit
489 // If no confirmations but it's from us, we can still
490 // consider it confirmed if all dependencies are confirmed
491 std::map<uint256, const CMerkleTx*> mapPrev;
492 std::vector<const CMerkleTx*> vWorkQueue;
493 vWorkQueue.reserve(vtxPrev.size()+1);
494 vWorkQueue.push_back(this);
495 for (int i = 0; i < vWorkQueue.size(); i++)
497 const CMerkleTx* ptx = vWorkQueue[i];
501 if (ptx->GetDepthInMainChain() >= 1)
503 if (!pwallet->IsFromMe(*ptx))
507 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
508 mapPrev[tx.GetHash()] = &tx;
510 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
512 if (!mapPrev.count(txin.prevout.hash))
514 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
522 int64 GetTxTime() const;
523 int GetRequestCount() const;
525 void AddSupportingTransactions(CTxDB& txdb);
527 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
528 bool AcceptWalletTransaction();
530 void RelayWalletTransaction(CTxDB& txdb);
531 void RelayWalletTransaction();
536 // Private key that includes an expiration date in case it never gets used.
544 std::string strComment;
545 //// todo: add something to note what created it (user, getnewaddress, change)
546 //// maybe should have a map<string, string> property map
548 CWalletKey(int64 nExpires=0)
550 nTimeCreated = (nExpires ? GetTime() : 0);
551 nTimeExpires = nExpires;
556 if (!(nType & SER_GETHASH))
558 READWRITE(vchPrivKey);
559 READWRITE(nTimeCreated);
560 READWRITE(nTimeExpires);
561 READWRITE(strComment);
571 // Account information.
572 // Stored in wallet with key "acc"+string account name
577 std::vector<unsigned char> vchPubKey;
591 if (!(nType & SER_GETHASH))
593 READWRITE(vchPubKey);
600 // Internal transfers.
601 // Database key is acentry<account><counter>
603 class CAccountingEntry
606 std::string strAccount;
609 std::string strOtherAccount;
610 std::string strComment;
622 strOtherAccount.clear();
628 if (!(nType & SER_GETHASH))
630 // Note: strAccount is serialized as part of the key, not here.
631 READWRITE(nCreditDebit);
633 READWRITE(strOtherAccount);
634 READWRITE(strComment);
638 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);