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;
24 class CAccountingEntry;
30 /** (client) version numbers for particular wallet features */
33 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
35 FEATURE_WALLETCRYPT = 40000, // wallet encryption
36 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
38 FEATURE_LATEST = 60000
41 /** A key pool entry */
53 CKeyPool(const CPubKey& vchPubKeyIn)
56 vchPubKey = vchPubKeyIn;
61 if (!(nType & SER_GETHASH))
68 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
69 * and provides the ability to create new transactions.
71 class CWallet : public CCryptoKeyStore
74 bool SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
75 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl *coinControl=NULL) const;
77 CWalletDB *pwalletdbEncryption;
79 // the current wallet version: clients below this version are not able to load the wallet
82 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
83 int nWalletMaxVersion;
85 // Used to detect and report conflicted transactions:
86 typedef std::multimap<COutPoint, uint256> TxConflicts;
87 TxConflicts mapTxConflicts;
88 void AddToConflicts(const uint256& wtxhash);
89 void SyncMetaData(std::pair<TxConflicts::iterator, TxConflicts::iterator>);
92 mutable CCriticalSection cs_wallet;
95 std::string strWalletFile;
97 std::set<int64> setKeyPool;
98 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
101 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
102 MasterKeyMap mapMasterKeys;
103 unsigned int nMasterKeyMaxID;
107 nWalletVersion = FEATURE_BASE;
108 nWalletMaxVersion = FEATURE_BASE;
111 pwalletdbEncryption = NULL;
114 CWallet(std::string strWalletFileIn)
116 nWalletVersion = FEATURE_BASE;
117 nWalletMaxVersion = FEATURE_BASE;
118 strWalletFile = strWalletFileIn;
121 pwalletdbEncryption = NULL;
125 std::map<uint256, CWalletTx> mapWallet;
127 std::map<uint256, int> mapRequestCount;
129 std::map<CTxDestination, std::string> mapAddressBook;
131 CPubKey vchDefaultKey;
134 // check whether we are allowed to upgrade (or already support) to the named feature
135 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
137 void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf) const;
138 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
139 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;
140 // keystore implementation
141 // Generate a new key
142 CPubKey GenerateNewKey();
143 // Adds a key to the store, and saves it to disk.
144 bool AddKey(const CKey& key);
145 // Adds a key to the store, without saving it to disk (used by LoadWallet)
146 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
147 // Load metadata (used by LoadWallet)
148 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
150 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
152 // Adds an encrypted key to the store, and saves it to disk.
153 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
154 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
155 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
156 bool AddCScript(const CScript& redeemScript);
157 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
159 bool Unlock(const SecureString& strWalletPassphrase);
160 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
161 bool EncryptWallet(const SecureString& strWalletPassphrase);
163 void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
166 /** Increment the next transaction order id
167 @return next transaction order id
169 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
171 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
172 typedef std::multimap<int64, TxPair > TxItems;
174 /** Get the wallet's activity log
175 @return multimap of ordered transactions and accounting entries
176 @warning Returned pointers are *only* valid within the scope of passed acentries
178 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
181 bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet=false);
182 bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
183 bool EraseFromWallet(uint256 hash);
184 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
185 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
186 void ReacceptWalletTransactions();
187 void ResendWalletTransactions(bool fForce=false);
188 int64 GetBalance() const;
189 int64 GetUnconfirmedBalance() const;
190 int64 GetImmatureBalance() const;
191 int64 GetStake() const;
192 int64 GetNewMint() const;
193 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
194 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
195 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
197 bool GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight);
198 void GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight);
199 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key);
201 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
202 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
205 bool TopUpKeyPool(unsigned int nSize = 0);
206 int64 AddReserveKey(const CKeyPool& keypool);
207 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
208 void KeepKey(int64 nIndex);
209 void ReturnKey(int64 nIndex);
210 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
211 int64 GetOldestKeyPoolTime();
212 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
214 std::set< std::set<CTxDestination> > GetAddressGroupings();
215 std::map<CTxDestination, int64> GetAddressBalances();
217 bool IsMine(const CTxIn& txin) const;
218 int64 GetDebit(const CTxIn& txin) const;
219 bool IsMine(const CTxOut& txout) const
221 return ::IsMine(*this, txout.scriptPubKey);
223 int64 GetCredit(const CTxOut& txout) const
225 if (!MoneyRange(txout.nValue))
226 throw std::runtime_error("CWallet::GetCredit() : value out of range");
227 return (IsMine(txout) ? txout.nValue : 0);
229 bool IsChange(const CTxOut& txout) const;
230 int64 GetChange(const CTxOut& txout) const
232 if (!MoneyRange(txout.nValue))
233 throw std::runtime_error("CWallet::GetChange() : value out of range");
234 return (IsChange(txout) ? txout.nValue : 0);
236 bool IsMine(const CTransaction& tx) const
238 BOOST_FOREACH(const CTxOut& txout, tx.vout)
239 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
243 bool IsFromMe(const CTransaction& tx) const
245 return (GetDebit(tx) > 0);
247 int64 GetDebit(const CTransaction& tx) const
250 BOOST_FOREACH(const CTxIn& txin, tx.vin)
252 nDebit += GetDebit(txin);
253 if (!MoneyRange(nDebit))
254 throw std::runtime_error("CWallet::GetDebit() : value out of range");
258 int64 GetCredit(const CTransaction& tx) const
261 BOOST_FOREACH(const CTxOut& txout, tx.vout)
263 nCredit += GetCredit(txout);
264 if (!MoneyRange(nCredit))
265 throw std::runtime_error("CWallet::GetCredit() : value out of range");
269 int64 GetChange(const CTransaction& tx) const
272 BOOST_FOREACH(const CTxOut& txout, tx.vout)
274 nChange += GetChange(txout);
275 if (!MoneyRange(nChange))
276 throw std::runtime_error("CWallet::GetChange() : value out of range");
280 void SetBestChain(const CBlockLocator& loc);
282 DBErrors LoadWallet(bool& fFirstRunRet);
284 DBErrors ZapWalletTx();
286 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
288 bool DelAddressBookName(const CTxDestination& address);
290 void UpdatedTransaction(const uint256 &hashTx);
292 void PrintWallet(const CBlock& block);
294 void Inventory(const uint256 &hash)
298 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
299 if (mi != mapRequestCount.end())
304 unsigned int GetKeyPoolSize()
306 return setKeyPool.size();
309 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
311 bool SetDefaultKey(const CPubKey &vchPubKey);
313 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
314 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
316 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
317 bool SetMaxVersion(int nVersion);
319 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
320 int GetVersion() { return nWalletVersion; }
322 // get wallet transactions that conflict with given transaction (spend same outputs)
323 std::set<uint256> GetConflicts(const uint256& txid) const;
325 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
326 void DisableTransaction(const CTransaction &tx);
328 /** Address book entry changed.
329 * @note called with lock cs_wallet held.
331 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
333 /** Wallet transaction added, removed or updated.
334 * @note called with lock cs_wallet held.
336 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
339 /** A key allocated from the key pool. */
347 CReserveKey(CWallet* pwalletIn)
360 CPubKey GetReservedKey();
365 typedef std::map<std::string, std::string> mapValue_t;
368 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
370 if (!mapValue.count("n"))
372 nOrderPos = -1; // TODO: calculate elsewhere
375 nOrderPos = atoi64(mapValue["n"].c_str());
379 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
383 mapValue["n"] = i64tostr(nOrderPos);
387 /** A transaction with a bunch of additional info that only the owner cares about.
388 * It includes any unrecorded transactions needed to link it back to the block chain.
390 class CWalletTx : public CMerkleTx
393 const CWallet* pwallet;
396 std::vector<CMerkleTx> vtxPrev;
398 std::vector<std::pair<std::string, std::string> > vOrderForm;
399 unsigned int fTimeReceivedIsTxTime;
400 unsigned int nTimeReceived; // time received by this node
401 unsigned int nTimeSmart;
403 std::string strFromAccount;
404 std::vector<char> vfSpent; // which outputs are already spent
405 int64 nOrderPos; // position in ordered transaction list
408 mutable bool fDebitCached;
409 mutable bool fCreditCached;
410 mutable bool fAvailableCreditCached;
411 mutable bool fChangeCached;
412 mutable int64 nDebitCached;
413 mutable int64 nCreditCached;
414 mutable int64 nAvailableCreditCached;
415 mutable int64 nChangeCached;
422 CWalletTx(const CWallet* pwalletIn)
427 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
432 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
437 void Init(const CWallet* pwalletIn)
443 fTimeReceivedIsTxTime = false;
447 strFromAccount.clear();
449 fDebitCached = false;
450 fCreditCached = false;
451 fAvailableCreditCached = false;
452 fChangeCached = false;
455 nAvailableCreditCached = 0;
462 CWalletTx* pthis = const_cast<CWalletTx*>(this);
469 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
472 BOOST_FOREACH(char f, vfSpent)
474 str += (f ? '1' : '0');
478 pthis->mapValue["spent"] = str;
480 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
483 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
486 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
489 READWRITE(vOrderForm);
490 READWRITE(fTimeReceivedIsTxTime);
491 READWRITE(nTimeReceived);
497 pthis->strFromAccount = pthis->mapValue["fromaccount"];
499 if (mapValue.count("spent"))
500 BOOST_FOREACH(char c, pthis->mapValue["spent"])
501 pthis->vfSpent.push_back(c != '0');
503 pthis->vfSpent.assign(vout.size(), fSpent);
505 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
507 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
510 pthis->mapValue.erase("fromaccount");
511 pthis->mapValue.erase("version");
512 pthis->mapValue.erase("spent");
513 pthis->mapValue.erase("n");
514 pthis->mapValue.erase("timesmart");
517 // marks certain txout's as spent
518 // returns true if any update took place
519 bool UpdateSpent(const std::vector<char>& vfNewSpent)
521 bool fReturn = false;
522 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
524 if (i == vfSpent.size())
527 if (vfNewSpent[i] && !vfSpent[i])
531 fAvailableCreditCached = false;
537 // make sure balances are recalculated
540 fCreditCached = false;
541 fAvailableCreditCached = false;
542 fDebitCached = false;
543 fChangeCached = false;
546 void BindWallet(CWallet *pwalletIn)
552 void MarkSpent(unsigned int nOut)
554 if (nOut >= vout.size())
555 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
556 vfSpent.resize(vout.size());
559 vfSpent[nOut] = true;
560 fAvailableCreditCached = false;
564 void MarkUnspent(unsigned int nOut)
566 if (nOut >= vout.size())
567 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
568 vfSpent.resize(vout.size());
571 vfSpent[nOut] = false;
572 fAvailableCreditCached = false;
576 bool IsSpent(unsigned int nOut) const
578 if (nOut >= vout.size())
579 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
580 if (nOut >= vfSpent.size())
582 return (!!vfSpent[nOut]);
585 int64 GetDebit() const
591 nDebitCached = pwallet->GetDebit(*this);
596 int64 GetCredit(bool fUseCache=true) const
598 // Must wait until coinbase is safely deep enough in the chain before valuing it
599 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
602 // GetBalance can assume transactions in mapWallet won't change
603 if (fUseCache && fCreditCached)
604 return nCreditCached;
605 nCreditCached = pwallet->GetCredit(*this);
606 fCreditCached = true;
607 return nCreditCached;
610 int64 GetAvailableCredit(bool fUseCache=true) const
612 // Must wait until coinbase is safely deep enough in the chain before valuing it
613 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
616 if (fUseCache && fAvailableCreditCached)
617 return nAvailableCreditCached;
620 for (unsigned int i = 0; i < vout.size(); i++)
624 const CTxOut &txout = vout[i];
625 nCredit += pwallet->GetCredit(txout);
626 if (!MoneyRange(nCredit))
627 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
631 nAvailableCreditCached = nCredit;
632 fAvailableCreditCached = true;
637 int64 GetChange() const
640 return nChangeCached;
641 nChangeCached = pwallet->GetChange(*this);
642 fChangeCached = true;
643 return nChangeCached;
646 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
647 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
649 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
650 int64& nSent, int64& nFee) const;
652 bool IsFromMe() const
654 return (GetDebit() > 0);
657 bool IsTrusted() const
659 // Quick answer in most cases
662 int nDepth = GetDepthInMainChain();
667 if (fConfChange || !IsFromMe()) // using wtx's cached debit
670 // If no confirmations but it's from us, we can still
671 // consider it confirmed if all dependencies are confirmed
672 std::map<uint256, const CMerkleTx*> mapPrev;
673 std::vector<const CMerkleTx*> vWorkQueue;
674 vWorkQueue.reserve(vtxPrev.size()+1);
675 vWorkQueue.push_back(this);
676 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
678 const CMerkleTx* ptx = vWorkQueue[i];
682 int nPDepth = ptx->GetDepthInMainChain();
687 if (!pwallet->IsFromMe(*ptx))
692 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
693 mapPrev[tx.GetHash()] = &tx;
696 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
698 if (!mapPrev.count(txin.prevout.hash))
700 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
708 int64 GetTxTime() const;
709 int GetRequestCount() const;
711 void AddSupportingTransactions();
713 bool AcceptWalletTransaction(bool fCheckInputs=true);
714 void RelayWalletTransaction();
716 std::set<uint256> GetConflicts() const;
729 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
731 tx = txIn; i = iIn; nDepth = nDepthIn;
734 std::string ToString() const
736 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
741 printf("%s\n", ToString().c_str());
748 /** Private key that includes an expiration date in case it never gets used. */
755 std::string strComment;
756 //// todo: add something to note what created it (user, getnewaddress, change)
757 //// maybe should have a map<string, string> property map
759 CWalletKey(int64 nExpires=0)
761 nTimeCreated = (nExpires ? GetTime() : 0);
762 nTimeExpires = nExpires;
767 if (!(nType & SER_GETHASH))
769 READWRITE(vchPrivKey);
770 READWRITE(nTimeCreated);
771 READWRITE(nTimeExpires);
772 READWRITE(strComment);
781 /** Account information.
782 * Stored in wallet with key "acc"+string account name.
796 vchPubKey = CPubKey();
801 if (!(nType & SER_GETHASH))
803 READWRITE(vchPubKey);
809 /** Internal transfers.
810 * Database key is acentry<account><counter>.
812 class CAccountingEntry
815 std::string strAccount;
818 std::string strOtherAccount;
819 std::string strComment;
821 int64 nOrderPos; // position in ordered transaction list
834 strOtherAccount.clear();
841 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
842 if (!(nType & SER_GETHASH))
844 // Note: strAccount is serialized as part of the key, not here.
845 READWRITE(nCreditDebit);
847 READWRITE(strOtherAccount);
851 WriteOrderPos(nOrderPos, me.mapValue);
853 if (!(mapValue.empty() && _ssExtra.empty()))
855 CDataStream ss(nType, nVersion);
856 ss.insert(ss.begin(), '\0');
858 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
859 me.strComment.append(ss.str());
863 READWRITE(strComment);
865 size_t nSepPos = strComment.find("\0", 0, 1);
869 if (std::string::npos != nSepPos)
871 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
873 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
875 ReadOrderPos(me.nOrderPos, me.mapValue);
877 if (std::string::npos != nSepPos)
878 me.strComment.erase(nSepPos);
880 me.mapValue.erase("n");
884 std::vector<char> _ssExtra;
887 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);