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 license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_WALLET_H
6 #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, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
24 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
26 CWalletDB *pwalletdbEncryption;
31 mutable CCriticalSection cs_wallet;
34 std::string strWalletFile;
36 std::set<int64> setKeyPool;
39 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
40 MasterKeyMap mapMasterKeys;
41 unsigned int nMasterKeyMaxID;
48 pwalletdbEncryption = NULL;
50 CWallet(std::string strWalletFileIn)
53 strWalletFile = strWalletFileIn;
56 pwalletdbEncryption = NULL;
59 std::map<uint256, CWalletTx> mapWallet;
60 std::vector<uint256> vWalletUpdated;
62 std::map<uint256, int> mapRequestCount;
64 std::map<CBitcoinAddress, std::string> mapAddressBook;
66 std::vector<unsigned char> vchDefaultKey;
68 // keystore implementation
70 std::vector<unsigned char> GenerateNewKey();
71 // Adds a key to the store, and saves it to disk.
72 bool AddKey(const CKey& key);
73 // Adds a key to the store, without saving it to disk (used by LoadWallet)
74 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
76 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; return true; }
78 // Adds an encrypted key to the store, and saves it to disk.
79 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
80 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
81 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
82 bool AddCScript(const CScript& redeemScript);
83 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
85 bool Unlock(const SecureString& strWalletPassphrase);
86 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
87 bool EncryptWallet(const SecureString& strWalletPassphrase);
90 bool AddToWallet(const CWalletTx& wtxIn);
91 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
92 bool EraseFromWallet(uint256 hash);
93 void WalletUpdateSpent(const CTransaction& prevout);
94 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
95 int ScanForWalletTransaction(const uint256& hashTx);
96 void ReacceptWalletTransactions();
97 void ResendWalletTransactions();
98 int64 GetBalance() const;
99 int64 GetUnconfirmedBalance() const;
100 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
101 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
102 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
103 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
104 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
108 int64 AddReserveKey(const CKeyPool& keypool);
109 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
110 void KeepKey(int64 nIndex);
111 void ReturnKey(int64 nIndex);
112 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
113 int64 GetOldestKeyPoolTime();
114 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
116 bool IsMine(const CTxIn& txin) const;
117 int64 GetDebit(const CTxIn& txin) const;
118 bool IsMine(const CTxOut& txout) const
120 return ::IsMine(*this, txout.scriptPubKey);
122 int64 GetCredit(const CTxOut& txout) const
124 if (!MoneyRange(txout.nValue))
125 throw std::runtime_error("CWallet::GetCredit() : value out of range");
126 return (IsMine(txout) ? txout.nValue : 0);
128 bool IsChange(const CTxOut& txout) const;
129 int64 GetChange(const CTxOut& txout) const
131 if (!MoneyRange(txout.nValue))
132 throw std::runtime_error("CWallet::GetChange() : value out of range");
133 return (IsChange(txout) ? txout.nValue : 0);
135 bool IsMine(const CTransaction& tx) const
137 BOOST_FOREACH(const CTxOut& txout, tx.vout)
142 bool IsFromMe(const CTransaction& tx) const
144 return (GetDebit(tx) > 0);
146 int64 GetDebit(const CTransaction& tx) const
149 BOOST_FOREACH(const CTxIn& txin, tx.vin)
151 nDebit += GetDebit(txin);
152 if (!MoneyRange(nDebit))
153 throw std::runtime_error("CWallet::GetDebit() : value out of range");
157 int64 GetCredit(const CTransaction& tx) const
160 BOOST_FOREACH(const CTxOut& txout, tx.vout)
162 nCredit += GetCredit(txout);
163 if (!MoneyRange(nCredit))
164 throw std::runtime_error("CWallet::GetCredit() : value out of range");
168 int64 GetChange(const CTransaction& tx) const
171 BOOST_FOREACH(const CTxOut& txout, tx.vout)
173 nChange += GetChange(txout);
174 if (!MoneyRange(nChange))
175 throw std::runtime_error("CWallet::GetChange() : value out of range");
179 void SetBestChain(const CBlockLocator& loc)
181 CWalletDB walletdb(strWalletFile);
182 walletdb.WriteBestBlock(loc);
185 int LoadWallet(bool& fFirstRunRet);
186 // bool BackupWallet(const std::string& strDest);
188 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
190 bool DelAddressBookName(const CBitcoinAddress& address);
192 void UpdatedTransaction(const uint256 &hashTx)
194 CRITICAL_BLOCK(cs_wallet)
195 vWalletUpdated.push_back(hashTx);
198 void PrintWallet(const CBlock& block);
200 void Inventory(const uint256 &hash)
202 CRITICAL_BLOCK(cs_wallet)
204 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
205 if (mi != mapRequestCount.end())
212 return setKeyPool.size();
215 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
217 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
219 bool SetMinVersion(int nVersion, CWalletDB* pwalletdbIn = NULL);
228 std::vector<unsigned char> vchPubKey;
230 CReserveKey(CWallet* pwalletIn)
243 std::vector<unsigned char> GetReservedKey();
249 // A transaction with a bunch of additional info that only the owner cares
250 // about. It includes any unrecorded transactions needed to link it back
251 // to the block chain.
253 class CWalletTx : public CMerkleTx
256 const CWallet* pwallet;
259 std::vector<CMerkleTx> vtxPrev;
260 std::map<std::string, std::string> mapValue;
261 std::vector<std::pair<std::string, std::string> > vOrderForm;
262 unsigned int fTimeReceivedIsTxTime;
263 unsigned int nTimeReceived; // time received by this node
265 std::string strFromAccount;
266 std::vector<char> vfSpent; // which outputs are already spent
269 mutable char fDebitCached;
270 mutable char fCreditCached;
271 mutable char fAvailableCreditCached;
272 mutable char fChangeCached;
273 mutable int64 nDebitCached;
274 mutable int64 nCreditCached;
275 mutable int64 nAvailableCreditCached;
276 mutable int64 nChangeCached;
278 // memory only UI hints
279 mutable unsigned int nTimeDisplayed;
280 mutable int nLinesDisplayed;
281 mutable char fConfirmedDisplayed;
288 CWalletTx(const CWallet* pwalletIn)
293 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
298 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
303 void Init(const CWallet* pwalletIn)
309 fTimeReceivedIsTxTime = false;
312 strFromAccount.clear();
314 fDebitCached = false;
315 fCreditCached = false;
316 fAvailableCreditCached = false;
317 fChangeCached = false;
320 nAvailableCreditCached = 0;
324 fConfirmedDisplayed = false;
329 CWalletTx* pthis = const_cast<CWalletTx*>(this);
336 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
339 BOOST_FOREACH(char f, vfSpent)
341 str += (f ? '1' : '0');
345 pthis->mapValue["spent"] = str;
348 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
351 READWRITE(vOrderForm);
352 READWRITE(fTimeReceivedIsTxTime);
353 READWRITE(nTimeReceived);
359 pthis->strFromAccount = pthis->mapValue["fromaccount"];
361 if (mapValue.count("spent"))
362 BOOST_FOREACH(char c, pthis->mapValue["spent"])
363 pthis->vfSpent.push_back(c != '0');
365 pthis->vfSpent.assign(vout.size(), fSpent);
368 pthis->mapValue.erase("fromaccount");
369 pthis->mapValue.erase("version");
370 pthis->mapValue.erase("spent");
373 // marks certain txout's as spent
374 // returns true if any update took place
375 bool UpdateSpent(const std::vector<char>& vfNewSpent)
377 bool fReturn = false;
378 for (int i=0; i < vfNewSpent.size(); i++)
380 if (i == vfSpent.size())
383 if (vfNewSpent[i] && !vfSpent[i])
387 fAvailableCreditCached = false;
393 // make sure balances are recalculated
396 fCreditCached = false;
397 fAvailableCreditCached = false;
398 fDebitCached = false;
399 fChangeCached = false;
402 void BindWallet(CWallet *pwalletIn)
408 void MarkSpent(unsigned int nOut)
410 if (nOut >= vout.size())
411 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
412 vfSpent.resize(vout.size());
415 vfSpent[nOut] = true;
416 fAvailableCreditCached = false;
420 bool IsSpent(unsigned int nOut) const
422 if (nOut >= vout.size())
423 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
424 if (nOut >= vfSpent.size())
426 return (!!vfSpent[nOut]);
429 int64 GetDebit() const
435 nDebitCached = pwallet->GetDebit(*this);
440 int64 GetCredit(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 // GetBalance can assume transactions in mapWallet won't change
447 if (fUseCache && fCreditCached)
448 return nCreditCached;
449 nCreditCached = pwallet->GetCredit(*this);
450 fCreditCached = true;
451 return nCreditCached;
454 int64 GetAvailableCredit(bool fUseCache=true) const
456 // Must wait until coinbase is safely deep enough in the chain before valuing it
457 if (IsCoinBase() && GetBlocksToMaturity() > 0)
460 if (fUseCache && fAvailableCreditCached)
461 return nAvailableCreditCached;
464 for (int i = 0; i < vout.size(); i++)
468 const CTxOut &txout = vout[i];
469 nCredit += pwallet->GetCredit(txout);
470 if (!MoneyRange(nCredit))
471 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
475 nAvailableCreditCached = nCredit;
476 fAvailableCreditCached = true;
481 int64 GetChange() const
484 return nChangeCached;
485 nChangeCached = pwallet->GetChange(*this);
486 fChangeCached = true;
487 return nChangeCached;
490 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
491 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
493 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
494 int64& nSent, int64& nFee) const;
496 bool IsFromMe() const
498 return (GetDebit() > 0);
501 bool IsConfirmed() const
503 // Quick answer in most cases
506 if (GetDepthInMainChain() >= 1)
508 if (!IsFromMe()) // using wtx's cached debit
511 // If no confirmations but it's from us, we can still
512 // consider it confirmed if all dependencies are confirmed
513 std::map<uint256, const CMerkleTx*> mapPrev;
514 std::vector<const CMerkleTx*> vWorkQueue;
515 vWorkQueue.reserve(vtxPrev.size()+1);
516 vWorkQueue.push_back(this);
517 for (int i = 0; i < vWorkQueue.size(); i++)
519 const CMerkleTx* ptx = vWorkQueue[i];
523 if (ptx->GetDepthInMainChain() >= 1)
525 if (!pwallet->IsFromMe(*ptx))
529 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
530 mapPrev[tx.GetHash()] = &tx;
532 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
534 if (!mapPrev.count(txin.prevout.hash))
536 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
544 int64 GetTxTime() const;
545 int GetRequestCount() const;
547 void AddSupportingTransactions(CTxDB& txdb);
549 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
550 bool AcceptWalletTransaction();
552 void RelayWalletTransaction(CTxDB& txdb);
553 void RelayWalletTransaction();
558 // Private key that includes an expiration date in case it never gets used.
566 std::string strComment;
567 //// todo: add something to note what created it (user, getnewaddress, change)
568 //// maybe should have a map<string, string> property map
570 CWalletKey(int64 nExpires=0)
572 nTimeCreated = (nExpires ? GetTime() : 0);
573 nTimeExpires = nExpires;
578 if (!(nType & SER_GETHASH))
580 READWRITE(vchPrivKey);
581 READWRITE(nTimeCreated);
582 READWRITE(nTimeExpires);
583 READWRITE(strComment);
593 // Account information.
594 // Stored in wallet with key "acc"+string account name
599 std::vector<unsigned char> vchPubKey;
613 if (!(nType & SER_GETHASH))
615 READWRITE(vchPubKey);
622 // Internal transfers.
623 // Database key is acentry<account><counter>
625 class CAccountingEntry
628 std::string strAccount;
631 std::string strOtherAccount;
632 std::string strComment;
644 strOtherAccount.clear();
650 if (!(nType & SER_GETHASH))
652 // Note: strAccount is serialized as part of the key, not here.
653 READWRITE(nCreditDebit);
655 READWRITE(strOtherAccount);
656 READWRITE(strComment);
660 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);