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 extern bool fWalletUnlockMintOnly;
22 class CAccountingEntry;
28 /** (client) version numbers for particular wallet features */
31 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
33 FEATURE_WALLETCRYPT = 40000, // wallet encryption
34 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
36 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 SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
73 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl *coinControl=NULL) const;
75 CWalletDB *pwalletdbEncryption;
77 // the current wallet version: clients below this version are not able to load the wallet
80 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
81 int nWalletMaxVersion;
84 mutable CCriticalSection cs_wallet;
87 std::string strWalletFile;
89 std::set<int64> setKeyPool;
90 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
93 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
94 MasterKeyMap mapMasterKeys;
95 unsigned int nMasterKeyMaxID;
99 nWalletVersion = FEATURE_BASE;
100 nWalletMaxVersion = FEATURE_BASE;
103 pwalletdbEncryption = NULL;
106 CWallet(std::string strWalletFileIn)
108 nWalletVersion = FEATURE_BASE;
109 nWalletMaxVersion = FEATURE_BASE;
110 strWalletFile = strWalletFileIn;
113 pwalletdbEncryption = NULL;
117 std::map<uint256, CWalletTx> mapWallet;
119 std::map<uint256, int> mapRequestCount;
121 std::map<CTxDestination, std::string> mapAddressBook;
123 CPubKey vchDefaultKey;
126 // check whether we are allowed to upgrade (or already support) to the named feature
127 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
129 void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf) const;
130 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
131 bool SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
132 // keystore implementation
133 // Generate a new key
134 CPubKey GenerateNewKey();
135 // Adds a key to the store, and saves it to disk.
136 bool AddKey(const CKey& key);
137 // Adds a key to the store, without saving it to disk (used by LoadWallet)
138 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
139 // Load metadata (used by LoadWallet)
140 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
142 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
144 // Adds an encrypted key to the store, and saves it to disk.
145 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
146 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
147 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
148 bool AddCScript(const CScript& redeemScript);
149 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
151 bool Unlock(const SecureString& strWalletPassphrase);
152 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
153 bool EncryptWallet(const SecureString& strWalletPassphrase);
155 void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
158 /** Increment the next transaction order id
159 @return next transaction order id
161 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
163 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
164 typedef std::multimap<int64, TxPair > TxItems;
166 /** Get the wallet's activity log
167 @return multimap of ordered transactions and accounting entries
168 @warning Returned pointers are *only* valid within the scope of passed acentries
170 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
173 bool AddToWallet(const CWalletTx& wtxIn);
174 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
175 bool EraseFromWallet(uint256 hash);
176 void WalletUpdateSpent(const CTransaction& prevout);
177 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
178 int ScanForWalletTransaction(const uint256& hashTx);
179 void ReacceptWalletTransactions();
180 void ResendWalletTransactions();
181 int64 GetBalance() const;
182 int64 GetUnconfirmedBalance() const;
183 int64 GetImmatureBalance() const;
184 int64 GetStake() const;
185 int64 GetNewMint() const;
186 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
187 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
188 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
190 bool GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight);
191 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key);
193 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
194 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
197 bool TopUpKeyPool(unsigned int nSize = 0);
198 int64 AddReserveKey(const CKeyPool& keypool);
199 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
200 void KeepKey(int64 nIndex);
201 void ReturnKey(int64 nIndex);
202 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
203 int64 GetOldestKeyPoolTime();
204 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
206 std::set< std::set<CTxDestination> > GetAddressGroupings();
207 std::map<CTxDestination, int64> GetAddressBalances();
209 bool IsMine(const CTxIn& txin) const;
210 int64 GetDebit(const CTxIn& txin) const;
211 bool IsMine(const CTxOut& txout) const
213 return ::IsMine(*this, txout.scriptPubKey);
215 int64 GetCredit(const CTxOut& txout) const
217 if (!MoneyRange(txout.nValue))
218 throw std::runtime_error("CWallet::GetCredit() : value out of range");
219 return (IsMine(txout) ? txout.nValue : 0);
221 bool IsChange(const CTxOut& txout) const;
222 int64 GetChange(const CTxOut& txout) const
224 if (!MoneyRange(txout.nValue))
225 throw std::runtime_error("CWallet::GetChange() : value out of range");
226 return (IsChange(txout) ? txout.nValue : 0);
228 bool IsMine(const CTransaction& tx) const
230 BOOST_FOREACH(const CTxOut& txout, tx.vout)
231 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
235 bool IsFromMe(const CTransaction& tx) const
237 return (GetDebit(tx) > 0);
239 int64 GetDebit(const CTransaction& tx) const
242 BOOST_FOREACH(const CTxIn& txin, tx.vin)
244 nDebit += GetDebit(txin);
245 if (!MoneyRange(nDebit))
246 throw std::runtime_error("CWallet::GetDebit() : value out of range");
250 int64 GetCredit(const CTransaction& tx) const
253 BOOST_FOREACH(const CTxOut& txout, tx.vout)
255 nCredit += GetCredit(txout);
256 if (!MoneyRange(nCredit))
257 throw std::runtime_error("CWallet::GetCredit() : value out of range");
261 int64 GetChange(const CTransaction& tx) const
264 BOOST_FOREACH(const CTxOut& txout, tx.vout)
266 nChange += GetChange(txout);
267 if (!MoneyRange(nChange))
268 throw std::runtime_error("CWallet::GetChange() : value out of range");
272 void SetBestChain(const CBlockLocator& loc);
274 DBErrors LoadWallet(bool& fFirstRunRet);
276 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
278 bool DelAddressBookName(const CTxDestination& address);
280 void UpdatedTransaction(const uint256 &hashTx);
282 void PrintWallet(const CBlock& block);
284 void Inventory(const uint256 &hash)
288 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
289 if (mi != mapRequestCount.end())
294 unsigned int GetKeyPoolSize()
296 return setKeyPool.size();
299 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
301 bool SetDefaultKey(const CPubKey &vchPubKey);
303 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
304 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
306 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
307 bool SetMaxVersion(int nVersion);
309 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
310 int GetVersion() { return nWalletVersion; }
312 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
313 void DisableTransaction(const CTransaction &tx);
315 /** Address book entry changed.
316 * @note called with lock cs_wallet held.
318 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
320 /** Wallet transaction added, removed or updated.
321 * @note called with lock cs_wallet held.
323 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
326 /** A key allocated from the key pool. */
334 CReserveKey(CWallet* pwalletIn)
347 CPubKey GetReservedKey();
352 typedef std::map<std::string, std::string> mapValue_t;
355 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
357 if (!mapValue.count("n"))
359 nOrderPos = -1; // TODO: calculate elsewhere
362 nOrderPos = atoi64(mapValue["n"].c_str());
366 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
370 mapValue["n"] = i64tostr(nOrderPos);
374 /** A transaction with a bunch of additional info that only the owner cares about.
375 * It includes any unrecorded transactions needed to link it back to the block chain.
377 class CWalletTx : public CMerkleTx
380 const CWallet* pwallet;
383 std::vector<CMerkleTx> vtxPrev;
385 std::vector<std::pair<std::string, std::string> > vOrderForm;
386 unsigned int fTimeReceivedIsTxTime;
387 unsigned int nTimeReceived; // time received by this node
388 unsigned int nTimeSmart;
390 std::string strFromAccount;
391 std::vector<char> vfSpent; // which outputs are already spent
392 int64 nOrderPos; // position in ordered transaction list
395 mutable bool fDebitCached;
396 mutable bool fCreditCached;
397 mutable bool fAvailableCreditCached;
398 mutable bool fChangeCached;
399 mutable int64 nDebitCached;
400 mutable int64 nCreditCached;
401 mutable int64 nAvailableCreditCached;
402 mutable int64 nChangeCached;
409 CWalletTx(const CWallet* pwalletIn)
414 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
419 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
424 void Init(const CWallet* pwalletIn)
430 fTimeReceivedIsTxTime = false;
434 strFromAccount.clear();
436 fDebitCached = false;
437 fCreditCached = false;
438 fAvailableCreditCached = false;
439 fChangeCached = false;
442 nAvailableCreditCached = 0;
449 CWalletTx* pthis = const_cast<CWalletTx*>(this);
456 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
459 BOOST_FOREACH(char f, vfSpent)
461 str += (f ? '1' : '0');
465 pthis->mapValue["spent"] = str;
467 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
470 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
473 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
476 READWRITE(vOrderForm);
477 READWRITE(fTimeReceivedIsTxTime);
478 READWRITE(nTimeReceived);
484 pthis->strFromAccount = pthis->mapValue["fromaccount"];
486 if (mapValue.count("spent"))
487 BOOST_FOREACH(char c, pthis->mapValue["spent"])
488 pthis->vfSpent.push_back(c != '0');
490 pthis->vfSpent.assign(vout.size(), fSpent);
492 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
494 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
497 pthis->mapValue.erase("fromaccount");
498 pthis->mapValue.erase("version");
499 pthis->mapValue.erase("spent");
500 pthis->mapValue.erase("n");
501 pthis->mapValue.erase("timesmart");
504 // marks certain txout's as spent
505 // returns true if any update took place
506 bool UpdateSpent(const std::vector<char>& vfNewSpent)
508 bool fReturn = false;
509 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
511 if (i == vfSpent.size())
514 if (vfNewSpent[i] && !vfSpent[i])
518 fAvailableCreditCached = false;
524 // make sure balances are recalculated
527 fCreditCached = false;
528 fAvailableCreditCached = false;
529 fDebitCached = false;
530 fChangeCached = false;
533 void BindWallet(CWallet *pwalletIn)
539 void MarkSpent(unsigned int nOut)
541 if (nOut >= vout.size())
542 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
543 vfSpent.resize(vout.size());
546 vfSpent[nOut] = true;
547 fAvailableCreditCached = false;
551 void MarkUnspent(unsigned int nOut)
553 if (nOut >= vout.size())
554 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
555 vfSpent.resize(vout.size());
558 vfSpent[nOut] = false;
559 fAvailableCreditCached = false;
563 bool IsSpent(unsigned int nOut) const
565 if (nOut >= vout.size())
566 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
567 if (nOut >= vfSpent.size())
569 return (!!vfSpent[nOut]);
572 int64 GetDebit() const
578 nDebitCached = pwallet->GetDebit(*this);
583 int64 GetCredit(bool fUseCache=true) const
585 // Must wait until coinbase is safely deep enough in the chain before valuing it
586 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
589 // GetBalance can assume transactions in mapWallet won't change
590 if (fUseCache && fCreditCached)
591 return nCreditCached;
592 nCreditCached = pwallet->GetCredit(*this);
593 fCreditCached = true;
594 return nCreditCached;
597 int64 GetAvailableCredit(bool fUseCache=true) const
599 // Must wait until coinbase is safely deep enough in the chain before valuing it
600 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
603 if (fUseCache && fAvailableCreditCached)
604 return nAvailableCreditCached;
607 for (unsigned int i = 0; i < vout.size(); i++)
611 const CTxOut &txout = vout[i];
612 nCredit += pwallet->GetCredit(txout);
613 if (!MoneyRange(nCredit))
614 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
618 nAvailableCreditCached = nCredit;
619 fAvailableCreditCached = true;
624 int64 GetChange() const
627 return nChangeCached;
628 nChangeCached = pwallet->GetChange(*this);
629 fChangeCached = true;
630 return nChangeCached;
633 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
634 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
636 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
637 int64& nSent, int64& nFee) const;
639 bool IsFromMe() const
641 return (GetDebit() > 0);
644 bool IsConfirmed() const
646 // Quick answer in most cases
649 if (GetDepthInMainChain() >= 1)
651 if (!IsFromMe()) // using wtx's cached debit
654 // If no confirmations but it's from us, we can still
655 // consider it confirmed if all dependencies are confirmed
656 std::map<uint256, const CMerkleTx*> mapPrev;
657 std::vector<const CMerkleTx*> vWorkQueue;
658 vWorkQueue.reserve(vtxPrev.size()+1);
659 vWorkQueue.push_back(this);
660 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
662 const CMerkleTx* ptx = vWorkQueue[i];
666 if (ptx->GetDepthInMainChain() >= 1)
668 if (!pwallet->IsFromMe(*ptx))
673 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
674 mapPrev[tx.GetHash()] = &tx;
677 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
679 if (!mapPrev.count(txin.prevout.hash))
681 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
689 int64 GetTxTime() const;
690 int GetRequestCount() const;
692 void AddSupportingTransactions(CTxDB& txdb);
694 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
695 bool AcceptWalletTransaction();
697 void RelayWalletTransaction(CTxDB& txdb);
698 void RelayWalletTransaction();
711 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
713 tx = txIn; i = iIn; nDepth = nDepthIn;
716 std::string ToString() const
718 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
723 printf("%s\n", ToString().c_str());
730 /** Private key that includes an expiration date in case it never gets used. */
737 std::string strComment;
738 //// todo: add something to note what created it (user, getnewaddress, change)
739 //// maybe should have a map<string, string> property map
741 CWalletKey(int64 nExpires=0)
743 nTimeCreated = (nExpires ? GetTime() : 0);
744 nTimeExpires = nExpires;
749 if (!(nType & SER_GETHASH))
751 READWRITE(vchPrivKey);
752 READWRITE(nTimeCreated);
753 READWRITE(nTimeExpires);
754 READWRITE(strComment);
763 /** Account information.
764 * Stored in wallet with key "acc"+string account name.
778 vchPubKey = CPubKey();
783 if (!(nType & SER_GETHASH))
785 READWRITE(vchPubKey);
791 /** Internal transfers.
792 * Database key is acentry<account><counter>.
794 class CAccountingEntry
797 std::string strAccount;
800 std::string strOtherAccount;
801 std::string strComment;
803 int64 nOrderPos; // position in ordered transaction list
816 strOtherAccount.clear();
823 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
824 if (!(nType & SER_GETHASH))
826 // Note: strAccount is serialized as part of the key, not here.
827 READWRITE(nCreditDebit);
829 READWRITE(strOtherAccount);
833 WriteOrderPos(nOrderPos, me.mapValue);
835 if (!(mapValue.empty() && _ssExtra.empty()))
837 CDataStream ss(nType, nVersion);
838 ss.insert(ss.begin(), '\0');
840 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
841 me.strComment.append(ss.str());
845 READWRITE(strComment);
847 size_t nSepPos = strComment.find("\0", 0, 1);
851 if (std::string::npos != nSepPos)
853 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
855 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
857 ReadOrderPos(me.nOrderPos, me.mapValue);
859 if (std::string::npos != nSepPos)
860 me.strComment.erase(nSepPos);
862 me.mapValue.erase("n");
866 std::vector<char> _ssExtra;
869 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);