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
17 #include "ui_interface.h"
21 class CAccountingEntry;
27 /** (client) version numbers for particular wallet features */
30 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
32 FEATURE_WALLETCRYPT = 40000, // wallet encryption
33 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
35 FEATURE_LATEST = 60000
39 /** A key pool entry */
51 CKeyPool(const CPubKey& vchPubKeyIn)
54 vchPubKey = vchPubKeyIn;
59 if (!(nType & SER_GETHASH))
66 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
67 * and provides the ability to create new transactions.
69 class CWallet : public CCryptoKeyStore
72 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl *coinControl=NULL) const;
74 CWalletDB *pwalletdbEncryption;
76 // the current wallet version: clients below this version are not able to load the wallet
79 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
80 int nWalletMaxVersion;
83 mutable CCriticalSection cs_wallet;
86 std::string strWalletFile;
88 std::set<int64> setKeyPool;
91 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
92 MasterKeyMap mapMasterKeys;
93 unsigned int nMasterKeyMaxID;
97 nWalletVersion = FEATURE_BASE;
98 nWalletMaxVersion = FEATURE_BASE;
101 pwalletdbEncryption = NULL;
104 CWallet(std::string strWalletFileIn)
106 nWalletVersion = FEATURE_BASE;
107 nWalletMaxVersion = FEATURE_BASE;
108 strWalletFile = strWalletFileIn;
111 pwalletdbEncryption = NULL;
115 std::map<uint256, CWalletTx> mapWallet;
117 std::map<uint256, int> mapRequestCount;
119 std::map<CTxDestination, std::string> mapAddressBook;
121 CPubKey vchDefaultKey;
123 std::set<COutPoint> setLockedCoins;
125 // check whether we are allowed to upgrade (or already support) to the named feature
126 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
128 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
129 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
130 bool IsLockedCoin(uint256 hash, unsigned int n) const;
131 void LockCoin(COutPoint& output);
132 void UnlockCoin(COutPoint& output);
133 void UnlockAllCoins();
134 void ListLockedCoins(std::vector<COutPoint>& vOutpts);
136 // keystore implementation
137 // Generate a new key
138 CPubKey GenerateNewKey();
139 // Adds a key to the store, and saves it to disk.
140 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
141 // Adds a key to the store, without saving it to disk (used by LoadWallet)
142 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
144 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
146 // Adds an encrypted key to the store, and saves it to disk.
147 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
148 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
149 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
150 bool AddCScript(const CScript& redeemScript);
151 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
153 bool Unlock(const SecureString& strWalletPassphrase);
154 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
155 bool EncryptWallet(const SecureString& strWalletPassphrase);
157 /** Increment the next transaction order id
158 @return next transaction order id
160 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
162 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
163 typedef std::multimap<int64, TxPair > TxItems;
165 /** Get the wallet's activity log
166 @return multimap of ordered transactions and accounting entries
167 @warning Returned pointers are *only* valid within the scope of passed acentries
169 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
172 bool AddToWallet(const CWalletTx& wtxIn);
173 bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
174 bool EraseFromWallet(uint256 hash);
175 void WalletUpdateSpent(const CTransaction& prevout);
176 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
177 void ReacceptWalletTransactions();
178 void ResendWalletTransactions();
179 int64 GetBalance() const;
180 int64 GetUnconfirmedBalance() const;
181 int64 GetImmatureBalance() const;
182 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend,
183 CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason, const CCoinControl *coinControl=NULL);
184 bool CreateTransaction(CScript scriptPubKey, int64 nValue,
185 CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason, const CCoinControl *coinControl=NULL);
186 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
187 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
188 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
192 int64 AddReserveKey(const CKeyPool& keypool);
193 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
194 void KeepKey(int64 nIndex);
195 void ReturnKey(int64 nIndex);
196 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
197 int64 GetOldestKeyPoolTime();
198 void GetAllReserveKeys(std::set<CKeyID>& setAddress);
200 std::set< std::set<CTxDestination> > GetAddressGroupings();
201 std::map<CTxDestination, int64> GetAddressBalances();
203 bool IsMine(const CTxIn& txin) const;
204 int64 GetDebit(const CTxIn& txin) const;
205 bool IsMine(const CTxOut& txout) const
207 return ::IsMine(*this, txout.scriptPubKey);
209 int64 GetCredit(const CTxOut& txout) const
211 if (!MoneyRange(txout.nValue))
212 throw std::runtime_error("CWallet::GetCredit() : value out of range");
213 return (IsMine(txout) ? txout.nValue : 0);
215 bool IsChange(const CTxOut& txout) const;
216 int64 GetChange(const CTxOut& txout) const
218 if (!MoneyRange(txout.nValue))
219 throw std::runtime_error("CWallet::GetChange() : value out of range");
220 return (IsChange(txout) ? txout.nValue : 0);
222 bool IsMine(const CTransaction& tx) const
224 BOOST_FOREACH(const CTxOut& txout, tx.vout)
225 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
229 bool IsFromMe(const CTransaction& tx) const
231 return (GetDebit(tx) > 0);
233 int64 GetDebit(const CTransaction& tx) const
236 BOOST_FOREACH(const CTxIn& txin, tx.vin)
238 nDebit += GetDebit(txin);
239 if (!MoneyRange(nDebit))
240 throw std::runtime_error("CWallet::GetDebit() : value out of range");
244 int64 GetCredit(const CTransaction& tx) const
247 BOOST_FOREACH(const CTxOut& txout, tx.vout)
249 nCredit += GetCredit(txout);
250 if (!MoneyRange(nCredit))
251 throw std::runtime_error("CWallet::GetCredit() : value out of range");
255 int64 GetChange(const CTransaction& tx) const
258 BOOST_FOREACH(const CTxOut& txout, tx.vout)
260 nChange += GetChange(txout);
261 if (!MoneyRange(nChange))
262 throw std::runtime_error("CWallet::GetChange() : value out of range");
266 void SetBestChain(const CBlockLocator& loc);
268 DBErrors LoadWallet(bool& fFirstRunRet);
270 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
272 bool DelAddressBookName(const CTxDestination& address);
274 void UpdatedTransaction(const uint256 &hashTx);
276 void PrintWallet(const CBlock& block);
278 void Inventory(const uint256 &hash)
282 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
283 if (mi != mapRequestCount.end())
290 return setKeyPool.size();
293 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
295 bool SetDefaultKey(const CPubKey &vchPubKey);
297 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
298 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
300 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
301 bool SetMaxVersion(int nVersion);
303 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
304 int GetVersion() { return nWalletVersion; }
306 /** Address book entry changed.
307 * @note called with lock cs_wallet held.
309 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
311 /** Wallet transaction added, removed or updated.
312 * @note called with lock cs_wallet held.
314 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
317 /** A key allocated from the key pool. */
325 CReserveKey(CWallet* pwalletIn)
337 bool GetReservedKey(CPubKey &pubkey);
342 typedef std::map<std::string, std::string> mapValue_t;
345 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
347 if (!mapValue.count("n"))
349 nOrderPos = -1; // TODO: calculate elsewhere
352 nOrderPos = atoi64(mapValue["n"].c_str());
356 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
360 mapValue["n"] = i64tostr(nOrderPos);
364 /** A transaction with a bunch of additional info that only the owner cares about.
365 * It includes any unrecorded transactions needed to link it back to the block chain.
367 class CWalletTx : public CMerkleTx
370 const CWallet* pwallet;
373 std::vector<CMerkleTx> vtxPrev;
375 std::vector<std::pair<std::string, std::string> > vOrderForm;
376 unsigned int fTimeReceivedIsTxTime;
377 unsigned int nTimeReceived; // time received by this node
378 unsigned int nTimeSmart;
380 std::string strFromAccount;
381 std::vector<char> vfSpent; // which outputs are already spent
382 int64 nOrderPos; // position in ordered transaction list
385 mutable bool fDebitCached;
386 mutable bool fCreditCached;
387 mutable bool fImmatureCreditCached;
388 mutable bool fAvailableCreditCached;
389 mutable bool fChangeCached;
390 mutable int64 nDebitCached;
391 mutable int64 nCreditCached;
392 mutable int64 nImmatureCreditCached;
393 mutable int64 nAvailableCreditCached;
394 mutable int64 nChangeCached;
401 CWalletTx(const CWallet* pwalletIn)
406 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
411 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
416 void Init(const CWallet* pwalletIn)
422 fTimeReceivedIsTxTime = false;
426 strFromAccount.clear();
428 fDebitCached = false;
429 fCreditCached = false;
430 fImmatureCreditCached = false;
431 fAvailableCreditCached = false;
432 fChangeCached = false;
435 nImmatureCreditCached = 0;
436 nAvailableCreditCached = 0;
443 CWalletTx* pthis = const_cast<CWalletTx*>(this);
450 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
453 BOOST_FOREACH(char f, vfSpent)
455 str += (f ? '1' : '0');
459 pthis->mapValue["spent"] = str;
461 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
464 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
467 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
470 READWRITE(vOrderForm);
471 READWRITE(fTimeReceivedIsTxTime);
472 READWRITE(nTimeReceived);
478 pthis->strFromAccount = pthis->mapValue["fromaccount"];
480 if (mapValue.count("spent"))
481 BOOST_FOREACH(char c, pthis->mapValue["spent"])
482 pthis->vfSpent.push_back(c != '0');
484 pthis->vfSpent.assign(vout.size(), fSpent);
486 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
488 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
491 pthis->mapValue.erase("fromaccount");
492 pthis->mapValue.erase("version");
493 pthis->mapValue.erase("spent");
494 pthis->mapValue.erase("n");
495 pthis->mapValue.erase("timesmart");
498 // marks certain txout's as spent
499 // returns true if any update took place
500 bool UpdateSpent(const std::vector<char>& vfNewSpent)
502 bool fReturn = false;
503 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
505 if (i == vfSpent.size())
508 if (vfNewSpent[i] && !vfSpent[i])
512 fAvailableCreditCached = false;
518 // make sure balances are recalculated
521 fCreditCached = false;
522 fAvailableCreditCached = false;
523 fDebitCached = false;
524 fChangeCached = false;
527 void BindWallet(CWallet *pwalletIn)
533 void MarkSpent(unsigned int nOut)
535 if (nOut >= vout.size())
536 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
537 vfSpent.resize(vout.size());
540 vfSpent[nOut] = true;
541 fAvailableCreditCached = false;
545 bool IsSpent(unsigned int nOut) const
547 if (nOut >= vout.size())
548 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
549 if (nOut >= vfSpent.size())
551 return (!!vfSpent[nOut]);
554 int64 GetDebit() const
560 nDebitCached = pwallet->GetDebit(*this);
565 int64 GetCredit(bool fUseCache=true) const
567 // Must wait until coinbase is safely deep enough in the chain before valuing it
568 if (IsCoinBase() && GetBlocksToMaturity() > 0)
571 // GetBalance can assume transactions in mapWallet won't change
572 if (fUseCache && fCreditCached)
573 return nCreditCached;
574 nCreditCached = pwallet->GetCredit(*this);
575 fCreditCached = true;
576 return nCreditCached;
579 int64 GetImmatureCredit(bool fUseCache=true) const
581 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
583 if (fUseCache && fImmatureCreditCached)
584 return nImmatureCreditCached;
585 nImmatureCreditCached = pwallet->GetCredit(*this);
586 fImmatureCreditCached = true;
587 return nImmatureCreditCached;
593 int64 GetAvailableCredit(bool fUseCache=true) const
595 // Must wait until coinbase is safely deep enough in the chain before valuing it
596 if (IsCoinBase() && GetBlocksToMaturity() > 0)
599 if (fUseCache && fAvailableCreditCached)
600 return nAvailableCreditCached;
603 for (unsigned int i = 0; i < vout.size(); i++)
607 const CTxOut &txout = vout[i];
608 nCredit += pwallet->GetCredit(txout);
609 if (!MoneyRange(nCredit))
610 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
614 nAvailableCreditCached = nCredit;
615 fAvailableCreditCached = true;
620 int64 GetChange() const
623 return nChangeCached;
624 nChangeCached = pwallet->GetChange(*this);
625 fChangeCached = true;
626 return nChangeCached;
629 void GetAmounts(std::list<std::pair<CTxDestination, int64> >& listReceived,
630 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
632 void GetAccountAmounts(const std::string& strAccount, int64& nReceived,
633 int64& nSent, int64& nFee) const;
635 bool IsFromMe() const
637 return (GetDebit() > 0);
640 bool IsConfirmed() const
642 // Quick answer in most cases
645 if (GetDepthInMainChain() >= 1)
647 if (!IsFromMe()) // using wtx's cached debit
650 // If no confirmations but it's from us, we can still
651 // consider it confirmed if all dependencies are confirmed
652 std::map<uint256, const CMerkleTx*> mapPrev;
653 std::vector<const CMerkleTx*> vWorkQueue;
654 vWorkQueue.reserve(vtxPrev.size()+1);
655 vWorkQueue.push_back(this);
656 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
658 const CMerkleTx* ptx = vWorkQueue[i];
662 if (ptx->GetDepthInMainChain() >= 1)
664 if (!pwallet->IsFromMe(*ptx))
669 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
670 mapPrev[tx.GetHash()] = &tx;
673 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
675 if (!mapPrev.count(txin.prevout.hash))
677 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
685 int64 GetTxTime() const;
686 int GetRequestCount() const;
688 void AddSupportingTransactions();
689 bool AcceptWalletTransaction(bool fCheckInputs=true);
690 void RelayWalletTransaction();
703 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
705 tx = txIn; i = iIn; nDepth = nDepthIn;
708 std::string ToString() const
710 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
715 printf("%s\n", ToString().c_str());
722 /** Private key that includes an expiration date in case it never gets used. */
729 std::string strComment;
730 //// todo: add something to note what created it (user, getnewaddress, change)
731 //// maybe should have a map<string, string> property map
733 CWalletKey(int64 nExpires=0)
735 nTimeCreated = (nExpires ? GetTime() : 0);
736 nTimeExpires = nExpires;
741 if (!(nType & SER_GETHASH))
743 READWRITE(vchPrivKey);
744 READWRITE(nTimeCreated);
745 READWRITE(nTimeExpires);
746 READWRITE(strComment);
755 /** Account information.
756 * Stored in wallet with key "acc"+string account name.
770 vchPubKey = CPubKey();
775 if (!(nType & SER_GETHASH))
777 READWRITE(vchPubKey);
783 /** Internal transfers.
784 * Database key is acentry<account><counter>.
786 class CAccountingEntry
789 std::string strAccount;
792 std::string strOtherAccount;
793 std::string strComment;
795 int64 nOrderPos; // position in ordered transaction list
808 strOtherAccount.clear();
815 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
816 if (!(nType & SER_GETHASH))
818 // Note: strAccount is serialized as part of the key, not here.
819 READWRITE(nCreditDebit);
821 READWRITE(strOtherAccount);
825 WriteOrderPos(nOrderPos, me.mapValue);
827 if (!(mapValue.empty() && _ssExtra.empty()))
829 CDataStream ss(nType, nVersion);
830 ss.insert(ss.begin(), '\0');
832 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
833 me.strComment.append(ss.str());
837 READWRITE(strComment);
839 size_t nSepPos = strComment.find("\0", 0, 1);
843 if (std::string::npos != nSepPos)
845 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
847 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
849 ReadOrderPos(me.nOrderPos, me.mapValue);
851 if (std::string::npos != nSepPos)
852 me.strComment.erase(nSepPos);
854 me.mapValue.erase("n");
858 std::vector<char> _ssExtra;
861 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);