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 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 bool IsMine(const CTxIn& txin) const;
217 int64 GetDebit(const CTxIn& txin) const;
218 bool 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 DBErrors ZapWalletTx();
285 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
287 bool DelAddressBookName(const CTxDestination& address);
289 void UpdatedTransaction(const uint256 &hashTx);
291 void PrintWallet(const CBlock& block);
293 void Inventory(const uint256 &hash)
297 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
298 if (mi != mapRequestCount.end())
303 unsigned int GetKeyPoolSize()
305 return setKeyPool.size();
308 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
310 bool SetDefaultKey(const CPubKey &vchPubKey);
312 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
313 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
315 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
316 bool SetMaxVersion(int nVersion);
318 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
319 int GetVersion() { return nWalletVersion; }
321 // get wallet transactions that conflict with given transaction (spend same outputs)
322 std::set<uint256> GetConflicts(const uint256& txid) const;
324 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
325 void DisableTransaction(const CTransaction &tx);
327 /** Address book entry changed.
328 * @note called with lock cs_wallet held.
330 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
332 /** Wallet transaction added, removed or updated.
333 * @note called with lock cs_wallet held.
335 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
338 /** A key allocated from the key pool. */
346 CReserveKey(CWallet* pwalletIn)
359 CPubKey GetReservedKey();
364 typedef std::map<std::string, std::string> mapValue_t;
367 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
369 if (!mapValue.count("n"))
371 nOrderPos = -1; // TODO: calculate elsewhere
374 nOrderPos = atoi64(mapValue["n"].c_str());
378 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
382 mapValue["n"] = i64tostr(nOrderPos);
386 /** A transaction with a bunch of additional info that only the owner cares about.
387 * It includes any unrecorded transactions needed to link it back to the block chain.
389 class CWalletTx : public CMerkleTx
392 const CWallet* pwallet;
395 std::vector<CMerkleTx> vtxPrev;
397 std::vector<std::pair<std::string, std::string> > vOrderForm;
398 unsigned int fTimeReceivedIsTxTime;
399 unsigned int nTimeReceived; // time received by this node
400 unsigned int nTimeSmart;
402 std::string strFromAccount;
403 std::vector<char> vfSpent; // which outputs are already spent
404 int64 nOrderPos; // position in ordered transaction list
407 mutable bool fDebitCached;
408 mutable bool fCreditCached;
409 mutable bool fAvailableCreditCached;
410 mutable bool fChangeCached;
411 mutable int64 nDebitCached;
412 mutable int64 nCreditCached;
413 mutable int64 nAvailableCreditCached;
414 mutable int64 nChangeCached;
421 CWalletTx(const CWallet* pwalletIn)
426 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
431 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
436 void Init(const CWallet* pwalletIn)
442 fTimeReceivedIsTxTime = false;
446 strFromAccount.clear();
448 fDebitCached = false;
449 fCreditCached = false;
450 fAvailableCreditCached = false;
451 fChangeCached = false;
454 nAvailableCreditCached = 0;
461 CWalletTx* pthis = const_cast<CWalletTx*>(this);
468 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
471 BOOST_FOREACH(char f, vfSpent)
473 str += (f ? '1' : '0');
477 pthis->mapValue["spent"] = str;
479 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
482 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
485 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
488 READWRITE(vOrderForm);
489 READWRITE(fTimeReceivedIsTxTime);
490 READWRITE(nTimeReceived);
496 pthis->strFromAccount = pthis->mapValue["fromaccount"];
498 if (mapValue.count("spent"))
499 BOOST_FOREACH(char c, pthis->mapValue["spent"])
500 pthis->vfSpent.push_back(c != '0');
502 pthis->vfSpent.assign(vout.size(), fSpent);
504 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
506 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
509 pthis->mapValue.erase("fromaccount");
510 pthis->mapValue.erase("version");
511 pthis->mapValue.erase("spent");
512 pthis->mapValue.erase("n");
513 pthis->mapValue.erase("timesmart");
516 // marks certain txout's as spent
517 // returns true if any update took place
518 bool UpdateSpent(const std::vector<char>& vfNewSpent)
520 bool fReturn = false;
521 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
523 if (i == vfSpent.size())
526 if (vfNewSpent[i] && !vfSpent[i])
530 fAvailableCreditCached = false;
536 // make sure balances are recalculated
539 fCreditCached = false;
540 fAvailableCreditCached = false;
541 fDebitCached = false;
542 fChangeCached = false;
545 void BindWallet(CWallet *pwalletIn)
551 void MarkSpent(unsigned int nOut)
553 if (nOut >= vout.size())
554 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
555 vfSpent.resize(vout.size());
558 vfSpent[nOut] = true;
559 fAvailableCreditCached = false;
563 void MarkUnspent(unsigned int nOut)
565 if (nOut >= vout.size())
566 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
567 vfSpent.resize(vout.size());
570 vfSpent[nOut] = false;
571 fAvailableCreditCached = false;
575 bool IsSpent(unsigned int nOut) const
577 if (nOut >= vout.size())
578 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
579 if (nOut >= vfSpent.size())
581 return (!!vfSpent[nOut]);
584 int64 GetDebit() const
590 nDebitCached = pwallet->GetDebit(*this);
595 int64 GetCredit(bool fUseCache=true) const
597 // Must wait until coinbase is safely deep enough in the chain before valuing it
598 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
601 // GetBalance can assume transactions in mapWallet won't change
602 if (fUseCache && fCreditCached)
603 return nCreditCached;
604 nCreditCached = pwallet->GetCredit(*this);
605 fCreditCached = true;
606 return nCreditCached;
609 int64 GetAvailableCredit(bool fUseCache=true) const
611 // Must wait until coinbase is safely deep enough in the chain before valuing it
612 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
615 if (fUseCache && fAvailableCreditCached)
616 return nAvailableCreditCached;
619 for (unsigned int i = 0; i < vout.size(); i++)
623 const CTxOut &txout = vout[i];
624 nCredit += pwallet->GetCredit(txout);
625 if (!MoneyRange(nCredit))
626 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
630 nAvailableCreditCached = nCredit;
631 fAvailableCreditCached = true;
636 int64 GetChange() const
639 return nChangeCached;
640 nChangeCached = pwallet->GetChange(*this);
641 fChangeCached = true;
642 return nChangeCached;
645 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
646 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
648 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
649 int64& nSent, int64& nFee) const;
651 bool IsFromMe() const
653 return (GetDebit() > 0);
656 bool IsTrusted() const
658 // Quick answer in most cases
661 int nDepth = GetDepthInMainChain();
666 if (fConfChange || !IsFromMe()) // using wtx's cached debit
669 // If no confirmations but it's from us, we can still
670 // consider it confirmed if all dependencies are confirmed
671 std::map<uint256, const CMerkleTx*> mapPrev;
672 std::vector<const CMerkleTx*> vWorkQueue;
673 vWorkQueue.reserve(vtxPrev.size()+1);
674 vWorkQueue.push_back(this);
675 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
677 const CMerkleTx* ptx = vWorkQueue[i];
681 int nPDepth = ptx->GetDepthInMainChain();
686 if (!pwallet->IsFromMe(*ptx))
691 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
692 mapPrev[tx.GetHash()] = &tx;
695 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
697 if (!mapPrev.count(txin.prevout.hash))
699 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
707 int64 GetTxTime() const;
708 int GetRequestCount() const;
710 void AddSupportingTransactions();
712 bool AcceptWalletTransaction(bool fCheckInputs=true);
713 void RelayWalletTransaction();
715 std::set<uint256> GetConflicts() const;
728 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
730 tx = txIn; i = iIn; nDepth = nDepthIn;
733 std::string ToString() const
735 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
740 printf("%s\n", ToString().c_str());
747 /** Private key that includes an expiration date in case it never gets used. */
754 std::string strComment;
755 //// todo: add something to note what created it (user, getnewaddress, change)
756 //// maybe should have a map<string, string> property map
758 CWalletKey(int64 nExpires=0)
760 nTimeCreated = (nExpires ? GetTime() : 0);
761 nTimeExpires = nExpires;
766 if (!(nType & SER_GETHASH))
768 READWRITE(vchPrivKey);
769 READWRITE(nTimeCreated);
770 READWRITE(nTimeExpires);
771 READWRITE(strComment);
780 /** Account information.
781 * Stored in wallet with key "acc"+string account name.
795 vchPubKey = CPubKey();
800 if (!(nType & SER_GETHASH))
802 READWRITE(vchPubKey);
808 /** Internal transfers.
809 * Database key is acentry<account><counter>.
811 class CAccountingEntry
814 std::string strAccount;
817 std::string strOtherAccount;
818 std::string strComment;
820 int64 nOrderPos; // position in ordered transaction list
833 strOtherAccount.clear();
840 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
841 if (!(nType & SER_GETHASH))
843 // Note: strAccount is serialized as part of the key, not here.
844 READWRITE(nCreditDebit);
846 READWRITE(strOtherAccount);
850 WriteOrderPos(nOrderPos, me.mapValue);
852 if (!(mapValue.empty() && _ssExtra.empty()))
854 CDataStream ss(nType, nVersion);
855 ss.insert(ss.begin(), '\0');
857 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
858 me.strComment.append(ss.str());
862 READWRITE(strComment);
864 size_t nSepPos = strComment.find("\0", 0, 1);
868 if (std::string::npos != nSepPos)
870 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
872 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
874 ReadOrderPos(me.nOrderPos, me.mapValue);
876 if (std::string::npos != nSepPos)
877 me.strComment.erase(nSepPos);
879 me.mapValue.erase("n");
883 std::vector<char> _ssExtra;
886 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);