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 extern bool fConfChange;
23 class CAccountingEntry;
29 /** (client) version numbers for particular wallet features */
32 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
34 FEATURE_WALLETCRYPT = 40000, // wallet encryption
35 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
37 FEATURE_LATEST = 60000
40 /** A key pool entry */
52 CKeyPool(const CPubKey& vchPubKeyIn)
55 vchPubKey = vchPubKeyIn;
60 if (!(nType & SER_GETHASH))
67 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
68 * and provides the ability to create new transactions.
70 class CWallet : public CCryptoKeyStore
73 bool SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
74 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl *coinControl=NULL) const;
76 CWalletDB *pwalletdbEncryption;
78 // the current wallet version: clients below this version are not able to load the wallet
81 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
82 int nWalletMaxVersion;
85 mutable CCriticalSection cs_wallet;
88 std::string strWalletFile;
90 std::set<int64> setKeyPool;
91 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
94 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
95 MasterKeyMap mapMasterKeys;
96 unsigned int nMasterKeyMaxID;
100 nWalletVersion = FEATURE_BASE;
101 nWalletMaxVersion = FEATURE_BASE;
104 pwalletdbEncryption = NULL;
107 CWallet(std::string strWalletFileIn)
109 nWalletVersion = FEATURE_BASE;
110 nWalletMaxVersion = FEATURE_BASE;
111 strWalletFile = strWalletFileIn;
114 pwalletdbEncryption = NULL;
118 std::map<uint256, CWalletTx> mapWallet;
120 std::map<uint256, int> mapRequestCount;
122 std::map<CTxDestination, std::string> mapAddressBook;
124 CPubKey vchDefaultKey;
127 // check whether we are allowed to upgrade (or already support) to the named feature
128 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
130 void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf) const;
131 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
132 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;
133 // keystore implementation
134 // Generate a new key
135 CPubKey GenerateNewKey();
136 // Adds a key to the store, and saves it to disk.
137 bool AddKey(const CKey& key);
138 // Adds a key to the store, without saving it to disk (used by LoadWallet)
139 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
140 // Load metadata (used by LoadWallet)
141 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
143 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
145 // Adds an encrypted key to the store, and saves it to disk.
146 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
147 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
148 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
149 bool AddCScript(const CScript& redeemScript);
150 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
152 // Adds a watch-only address to the store, and saves it to disk.
153 bool AddWatchOnly(const CTxDestination &dest);
154 // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
155 bool LoadWatchOnly(const CTxDestination &dest);
157 bool Unlock(const SecureString& strWalletPassphrase);
158 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
159 bool EncryptWallet(const SecureString& strWalletPassphrase);
161 void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
164 /** Increment the next transaction order id
165 @return next transaction order id
167 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
169 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
170 typedef std::multimap<int64, TxPair > TxItems;
172 /** Get the wallet's activity log
173 @return multimap of ordered transactions and accounting entries
174 @warning Returned pointers are *only* valid within the scope of passed acentries
176 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
179 bool AddToWallet(const CWalletTx& wtxIn);
180 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
181 bool EraseFromWallet(uint256 hash);
182 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
183 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
184 int ScanForWalletTransaction(const uint256& hashTx);
185 void ReacceptWalletTransactions();
186 void ResendWalletTransactions();
187 int64 GetBalance() const;
188 int64 GetUnconfirmedBalance() const;
189 int64 GetImmatureBalance() const;
190 int64 GetStake() const;
191 int64 GetNewMint() const;
192 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
193 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
194 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
196 bool GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight);
197 void GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight);
198 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key);
200 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
201 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
204 bool TopUpKeyPool(unsigned int nSize = 0);
205 int64 AddReserveKey(const CKeyPool& keypool);
206 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
207 void KeepKey(int64 nIndex);
208 void ReturnKey(int64 nIndex);
209 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
210 int64 GetOldestKeyPoolTime();
211 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
213 std::set< std::set<CTxDestination> > GetAddressGroupings();
214 std::map<CTxDestination, int64> GetAddressBalances();
216 isminetype IsMine(const CTxIn& txin) const;
217 int64 GetDebit(const CTxIn& txin) const;
218 isminetype IsMine(const CTxOut& txout) const
220 return ::IsMine(*this, txout.scriptPubKey);
222 int64 GetCredit(const CTxOut& txout) const
224 if (!MoneyRange(txout.nValue))
225 throw std::runtime_error("CWallet::GetCredit() : value out of range");
226 return (IsMine(txout) ? txout.nValue : 0);
228 bool IsChange(const CTxOut& txout) const;
229 int64 GetChange(const CTxOut& txout) const
231 if (!MoneyRange(txout.nValue))
232 throw std::runtime_error("CWallet::GetChange() : value out of range");
233 return (IsChange(txout) ? txout.nValue : 0);
235 bool IsMine(const CTransaction& tx) const
237 BOOST_FOREACH(const CTxOut& txout, tx.vout)
238 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
242 bool IsFromMe(const CTransaction& tx) const
244 return (GetDebit(tx) > 0);
246 int64 GetDebit(const CTransaction& tx) const
249 BOOST_FOREACH(const CTxIn& txin, tx.vin)
251 nDebit += GetDebit(txin);
252 if (!MoneyRange(nDebit))
253 throw std::runtime_error("CWallet::GetDebit() : value out of range");
257 int64 GetCredit(const CTransaction& tx) const
260 BOOST_FOREACH(const CTxOut& txout, tx.vout)
262 nCredit += GetCredit(txout);
263 if (!MoneyRange(nCredit))
264 throw std::runtime_error("CWallet::GetCredit() : value out of range");
268 int64 GetChange(const CTransaction& tx) const
271 BOOST_FOREACH(const CTxOut& txout, tx.vout)
273 nChange += GetChange(txout);
274 if (!MoneyRange(nChange))
275 throw std::runtime_error("CWallet::GetChange() : value out of range");
279 void SetBestChain(const CBlockLocator& loc);
281 DBErrors LoadWallet(bool& fFirstRunRet);
283 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
285 bool DelAddressBookName(const CTxDestination& address);
287 void UpdatedTransaction(const uint256 &hashTx);
289 void PrintWallet(const CBlock& block);
291 void Inventory(const uint256 &hash)
295 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
296 if (mi != mapRequestCount.end())
301 unsigned int GetKeyPoolSize()
303 return setKeyPool.size();
306 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
308 bool SetDefaultKey(const CPubKey &vchPubKey);
310 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
311 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
313 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
314 bool SetMaxVersion(int nVersion);
316 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
317 int GetVersion() { return nWalletVersion; }
319 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
320 void DisableTransaction(const CTransaction &tx);
322 /** Address book entry changed.
323 * @note called with lock cs_wallet held.
325 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
327 /** Wallet transaction added, removed or updated.
328 * @note called with lock cs_wallet held.
330 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
333 /** A key allocated from the key pool. */
341 CReserveKey(CWallet* pwalletIn)
354 CPubKey GetReservedKey();
359 typedef std::map<std::string, std::string> mapValue_t;
362 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
364 if (!mapValue.count("n"))
366 nOrderPos = -1; // TODO: calculate elsewhere
369 nOrderPos = atoi64(mapValue["n"].c_str());
373 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
377 mapValue["n"] = i64tostr(nOrderPos);
381 /** A transaction with a bunch of additional info that only the owner cares about.
382 * It includes any unrecorded transactions needed to link it back to the block chain.
384 class CWalletTx : public CMerkleTx
387 const CWallet* pwallet;
390 std::vector<CMerkleTx> vtxPrev;
392 std::vector<std::pair<std::string, std::string> > vOrderForm;
393 unsigned int fTimeReceivedIsTxTime;
394 unsigned int nTimeReceived; // time received by this node
395 unsigned int nTimeSmart;
397 std::string strFromAccount;
398 std::vector<char> vfSpent; // which outputs are already spent
399 int64 nOrderPos; // position in ordered transaction list
402 mutable bool fDebitCached;
403 mutable bool fCreditCached;
404 mutable bool fAvailableCreditCached;
405 mutable bool fChangeCached;
406 mutable int64 nDebitCached;
407 mutable int64 nCreditCached;
408 mutable int64 nAvailableCreditCached;
409 mutable int64 nChangeCached;
416 CWalletTx(const CWallet* pwalletIn)
421 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
426 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
431 void Init(const CWallet* pwalletIn)
437 fTimeReceivedIsTxTime = false;
441 strFromAccount.clear();
443 fDebitCached = false;
444 fCreditCached = false;
445 fAvailableCreditCached = false;
446 fChangeCached = false;
449 nAvailableCreditCached = 0;
456 CWalletTx* pthis = const_cast<CWalletTx*>(this);
463 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
466 BOOST_FOREACH(char f, vfSpent)
468 str += (f ? '1' : '0');
472 pthis->mapValue["spent"] = str;
474 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
477 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
480 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
483 READWRITE(vOrderForm);
484 READWRITE(fTimeReceivedIsTxTime);
485 READWRITE(nTimeReceived);
491 pthis->strFromAccount = pthis->mapValue["fromaccount"];
493 if (mapValue.count("spent"))
494 BOOST_FOREACH(char c, pthis->mapValue["spent"])
495 pthis->vfSpent.push_back(c != '0');
497 pthis->vfSpent.assign(vout.size(), fSpent);
499 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
501 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
504 pthis->mapValue.erase("fromaccount");
505 pthis->mapValue.erase("version");
506 pthis->mapValue.erase("spent");
507 pthis->mapValue.erase("n");
508 pthis->mapValue.erase("timesmart");
511 // marks certain txout's as spent
512 // returns true if any update took place
513 bool UpdateSpent(const std::vector<char>& vfNewSpent)
515 bool fReturn = false;
516 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
518 if (i == vfSpent.size())
521 if (vfNewSpent[i] && !vfSpent[i])
525 fAvailableCreditCached = false;
531 // make sure balances are recalculated
534 fCreditCached = false;
535 fAvailableCreditCached = false;
536 fDebitCached = false;
537 fChangeCached = false;
540 void BindWallet(CWallet *pwalletIn)
546 void MarkSpent(unsigned int nOut)
548 if (nOut >= vout.size())
549 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
550 vfSpent.resize(vout.size());
553 vfSpent[nOut] = true;
554 fAvailableCreditCached = false;
558 void MarkUnspent(unsigned int nOut)
560 if (nOut >= vout.size())
561 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
562 vfSpent.resize(vout.size());
565 vfSpent[nOut] = false;
566 fAvailableCreditCached = false;
570 bool IsSpent(unsigned int nOut) const
572 if (nOut >= vout.size())
573 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
574 if (nOut >= vfSpent.size())
576 return (!!vfSpent[nOut]);
579 int64 GetDebit() const
585 nDebitCached = pwallet->GetDebit(*this);
590 int64 GetCredit(bool fUseCache=true) const
592 // Must wait until coinbase is safely deep enough in the chain before valuing it
593 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
596 // GetBalance can assume transactions in mapWallet won't change
597 if (fUseCache && fCreditCached)
598 return nCreditCached;
599 nCreditCached = pwallet->GetCredit(*this);
600 fCreditCached = true;
601 return nCreditCached;
604 int64 GetAvailableCredit(bool fUseCache=true) const
606 // Must wait until coinbase is safely deep enough in the chain before valuing it
607 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
610 if (fUseCache && fAvailableCreditCached)
611 return nAvailableCreditCached;
614 for (unsigned int i = 0; i < vout.size(); i++)
618 const CTxOut &txout = vout[i];
619 nCredit += pwallet->GetCredit(txout);
620 if (!MoneyRange(nCredit))
621 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
625 nAvailableCreditCached = nCredit;
626 fAvailableCreditCached = true;
631 int64 GetChange() const
634 return nChangeCached;
635 nChangeCached = pwallet->GetChange(*this);
636 fChangeCached = true;
637 return nChangeCached;
640 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
641 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
643 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
644 int64& nSent, int64& nFee) const;
646 bool IsFromMe() const
648 return (GetDebit() > 0);
651 bool IsTrusted() const
653 // Quick answer in most cases
656 if (GetDepthInMainChain() >= 1)
658 if (fConfChange || !IsFromMe()) // using wtx's cached debit
661 // If no confirmations but it's from us, we can still
662 // consider it confirmed if all dependencies are confirmed
663 std::map<uint256, const CMerkleTx*> mapPrev;
664 std::vector<const CMerkleTx*> vWorkQueue;
665 vWorkQueue.reserve(vtxPrev.size()+1);
666 vWorkQueue.push_back(this);
667 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
669 const CMerkleTx* ptx = vWorkQueue[i];
673 if (ptx->GetDepthInMainChain() >= 1)
675 if (!pwallet->IsFromMe(*ptx))
680 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
681 mapPrev[tx.GetHash()] = &tx;
684 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
686 if (!mapPrev.count(txin.prevout.hash))
688 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
697 int64 GetTxTime() const;
698 int GetRequestCount() const;
700 void AddSupportingTransactions(CTxDB& txdb);
702 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
703 bool AcceptWalletTransaction();
705 void RelayWalletTransaction(CTxDB& txdb);
706 void RelayWalletTransaction();
720 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
722 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
725 std::string ToString() const
727 return strprintf("COutput(%s, %d, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, fSpendable, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
732 printf("%s\n", ToString().c_str());
739 /** Private key that includes an expiration date in case it never gets used. */
746 std::string strComment;
747 //// todo: add something to note what created it (user, getnewaddress, change)
748 //// maybe should have a map<string, string> property map
750 CWalletKey(int64 nExpires=0)
752 nTimeCreated = (nExpires ? GetTime() : 0);
753 nTimeExpires = nExpires;
758 if (!(nType & SER_GETHASH))
760 READWRITE(vchPrivKey);
761 READWRITE(nTimeCreated);
762 READWRITE(nTimeExpires);
763 READWRITE(strComment);
772 /** Account information.
773 * Stored in wallet with key "acc"+string account name.
787 vchPubKey = CPubKey();
792 if (!(nType & SER_GETHASH))
794 READWRITE(vchPubKey);
800 /** Internal transfers.
801 * Database key is acentry<account><counter>.
803 class CAccountingEntry
806 std::string strAccount;
809 std::string strOtherAccount;
810 std::string strComment;
812 int64 nOrderPos; // position in ordered transaction list
825 strOtherAccount.clear();
832 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
833 if (!(nType & SER_GETHASH))
835 // Note: strAccount is serialized as part of the key, not here.
836 READWRITE(nCreditDebit);
838 READWRITE(strOtherAccount);
842 WriteOrderPos(nOrderPos, me.mapValue);
844 if (!(mapValue.empty() && _ssExtra.empty()))
846 CDataStream ss(nType, nVersion);
847 ss.insert(ss.begin(), '\0');
849 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
850 me.strComment.append(ss.str());
854 READWRITE(strComment);
856 size_t nSepPos = strComment.find("\0", 0, 1);
860 if (std::string::npos != nSepPos)
862 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
864 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
866 ReadOrderPos(me.nOrderPos, me.mapValue);
868 if (std::string::npos != nSepPos)
869 me.strComment.erase(nSepPos);
871 me.mapValue.erase("n");
875 std::vector<char> _ssExtra;
878 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);