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;
86 mutable CCriticalSection cs_wallet;
89 std::string strWalletFile;
91 std::set<int64> setKeyPool;
92 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
95 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
96 MasterKeyMap mapMasterKeys;
97 unsigned int nMasterKeyMaxID;
101 nWalletVersion = FEATURE_BASE;
102 nWalletMaxVersion = FEATURE_BASE;
105 pwalletdbEncryption = NULL;
108 CWallet(std::string strWalletFileIn)
110 nWalletVersion = FEATURE_BASE;
111 nWalletMaxVersion = FEATURE_BASE;
112 strWalletFile = strWalletFileIn;
115 pwalletdbEncryption = NULL;
119 std::map<uint256, CWalletTx> mapWallet;
121 std::map<uint256, int> mapRequestCount;
123 std::map<CTxDestination, std::string> mapAddressBook;
125 CPubKey vchDefaultKey;
128 // check whether we are allowed to upgrade (or already support) to the named feature
129 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
131 void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf) const;
132 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
133 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;
134 // keystore implementation
135 // Generate a new key
136 CPubKey GenerateNewKey();
137 // Adds a key to the store, and saves it to disk.
138 bool AddKey(const CKey& key);
139 // Adds a key to the store, without saving it to disk (used by LoadWallet)
140 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
141 // Load metadata (used by LoadWallet)
142 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
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) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, 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 void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
160 /** Increment the next transaction order id
161 @return next transaction order id
163 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
165 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
166 typedef std::multimap<int64, TxPair > TxItems;
168 /** Get the wallet's activity log
169 @return multimap of ordered transactions and accounting entries
170 @warning Returned pointers are *only* valid within the scope of passed acentries
172 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
175 bool AddToWallet(const CWalletTx& wtxIn);
176 bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
177 bool EraseFromWallet(uint256 hash);
178 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
179 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
180 void ReacceptWalletTransactions();
181 void ResendWalletTransactions(bool fForce=false);
182 int64 GetBalance() const;
183 int64 GetUnconfirmedBalance() const;
184 int64 GetImmatureBalance() const;
185 int64 GetStake() const;
186 int64 GetNewMint() const;
187 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
188 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
189 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
191 bool GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight);
192 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key);
194 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
195 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
198 bool TopUpKeyPool(unsigned int nSize = 0);
199 int64 AddReserveKey(const CKeyPool& keypool);
200 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
201 void KeepKey(int64 nIndex);
202 void ReturnKey(int64 nIndex);
203 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
204 int64 GetOldestKeyPoolTime();
205 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
207 std::set< std::set<CTxDestination> > GetAddressGroupings();
208 std::map<CTxDestination, int64> GetAddressBalances();
210 bool IsMine(const CTxIn& txin) const;
211 int64 GetDebit(const CTxIn& txin) const;
212 bool IsMine(const CTxOut& txout) const
214 return ::IsMine(*this, txout.scriptPubKey);
216 int64 GetCredit(const CTxOut& txout) const
218 if (!MoneyRange(txout.nValue))
219 throw std::runtime_error("CWallet::GetCredit() : value out of range");
220 return (IsMine(txout) ? txout.nValue : 0);
222 bool IsChange(const CTxOut& txout) const;
223 int64 GetChange(const CTxOut& txout) const
225 if (!MoneyRange(txout.nValue))
226 throw std::runtime_error("CWallet::GetChange() : value out of range");
227 return (IsChange(txout) ? txout.nValue : 0);
229 bool IsMine(const CTransaction& tx) const
231 BOOST_FOREACH(const CTxOut& txout, tx.vout)
232 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
236 bool IsFromMe(const CTransaction& tx) const
238 return (GetDebit(tx) > 0);
240 int64 GetDebit(const CTransaction& tx) const
243 BOOST_FOREACH(const CTxIn& txin, tx.vin)
245 nDebit += GetDebit(txin);
246 if (!MoneyRange(nDebit))
247 throw std::runtime_error("CWallet::GetDebit() : value out of range");
251 int64 GetCredit(const CTransaction& tx) const
254 BOOST_FOREACH(const CTxOut& txout, tx.vout)
256 nCredit += GetCredit(txout);
257 if (!MoneyRange(nCredit))
258 throw std::runtime_error("CWallet::GetCredit() : value out of range");
262 int64 GetChange(const CTransaction& tx) const
265 BOOST_FOREACH(const CTxOut& txout, tx.vout)
267 nChange += GetChange(txout);
268 if (!MoneyRange(nChange))
269 throw std::runtime_error("CWallet::GetChange() : value out of range");
273 void SetBestChain(const CBlockLocator& loc);
275 DBErrors LoadWallet(bool& fFirstRunRet);
277 DBErrors ZapWalletTx();
279 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
281 bool DelAddressBookName(const CTxDestination& address);
283 void UpdatedTransaction(const uint256 &hashTx);
285 void PrintWallet(const CBlock& block);
287 void Inventory(const uint256 &hash)
291 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
292 if (mi != mapRequestCount.end())
297 unsigned int GetKeyPoolSize()
299 return setKeyPool.size();
302 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
304 bool SetDefaultKey(const CPubKey &vchPubKey);
306 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
307 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
309 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
310 bool SetMaxVersion(int nVersion);
312 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
313 int GetVersion() { return nWalletVersion; }
315 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
316 void DisableTransaction(const CTransaction &tx);
318 /** Address book entry changed.
319 * @note called with lock cs_wallet held.
321 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
323 /** Wallet transaction added, removed or updated.
324 * @note called with lock cs_wallet held.
326 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
329 /** A key allocated from the key pool. */
337 CReserveKey(CWallet* pwalletIn)
350 CPubKey GetReservedKey();
355 typedef std::map<std::string, std::string> mapValue_t;
358 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
360 if (!mapValue.count("n"))
362 nOrderPos = -1; // TODO: calculate elsewhere
365 nOrderPos = atoi64(mapValue["n"].c_str());
369 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
373 mapValue["n"] = i64tostr(nOrderPos);
377 /** A transaction with a bunch of additional info that only the owner cares about.
378 * It includes any unrecorded transactions needed to link it back to the block chain.
380 class CWalletTx : public CMerkleTx
383 const CWallet* pwallet;
386 std::vector<CMerkleTx> vtxPrev;
388 std::vector<std::pair<std::string, std::string> > vOrderForm;
389 unsigned int fTimeReceivedIsTxTime;
390 unsigned int nTimeReceived; // time received by this node
391 unsigned int nTimeSmart;
393 std::string strFromAccount;
394 std::vector<char> vfSpent; // which outputs are already spent
395 int64 nOrderPos; // position in ordered transaction list
398 mutable bool fDebitCached;
399 mutable bool fCreditCached;
400 mutable bool fAvailableCreditCached;
401 mutable bool fChangeCached;
402 mutable int64 nDebitCached;
403 mutable int64 nCreditCached;
404 mutable int64 nAvailableCreditCached;
405 mutable int64 nChangeCached;
412 CWalletTx(const CWallet* pwalletIn)
417 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
422 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
427 void Init(const CWallet* pwalletIn)
433 fTimeReceivedIsTxTime = false;
437 strFromAccount.clear();
439 fDebitCached = false;
440 fCreditCached = false;
441 fAvailableCreditCached = false;
442 fChangeCached = false;
445 nAvailableCreditCached = 0;
452 CWalletTx* pthis = const_cast<CWalletTx*>(this);
459 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
462 BOOST_FOREACH(char f, vfSpent)
464 str += (f ? '1' : '0');
468 pthis->mapValue["spent"] = str;
470 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
473 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
476 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
479 READWRITE(vOrderForm);
480 READWRITE(fTimeReceivedIsTxTime);
481 READWRITE(nTimeReceived);
487 pthis->strFromAccount = pthis->mapValue["fromaccount"];
489 if (mapValue.count("spent"))
490 BOOST_FOREACH(char c, pthis->mapValue["spent"])
491 pthis->vfSpent.push_back(c != '0');
493 pthis->vfSpent.assign(vout.size(), fSpent);
495 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
497 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
500 pthis->mapValue.erase("fromaccount");
501 pthis->mapValue.erase("version");
502 pthis->mapValue.erase("spent");
503 pthis->mapValue.erase("n");
504 pthis->mapValue.erase("timesmart");
507 // marks certain txout's as spent
508 // returns true if any update took place
509 bool UpdateSpent(const std::vector<char>& vfNewSpent)
511 bool fReturn = false;
512 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
514 if (i == vfSpent.size())
517 if (vfNewSpent[i] && !vfSpent[i])
521 fAvailableCreditCached = false;
527 // make sure balances are recalculated
530 fCreditCached = false;
531 fAvailableCreditCached = false;
532 fDebitCached = false;
533 fChangeCached = false;
536 void BindWallet(CWallet *pwalletIn)
542 void MarkSpent(unsigned int nOut)
544 if (nOut >= vout.size())
545 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
546 vfSpent.resize(vout.size());
549 vfSpent[nOut] = true;
550 fAvailableCreditCached = false;
554 void MarkUnspent(unsigned int nOut)
556 if (nOut >= vout.size())
557 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
558 vfSpent.resize(vout.size());
561 vfSpent[nOut] = false;
562 fAvailableCreditCached = false;
566 bool IsSpent(unsigned int nOut) const
568 if (nOut >= vout.size())
569 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
570 if (nOut >= vfSpent.size())
572 return (!!vfSpent[nOut]);
575 int64 GetDebit() const
581 nDebitCached = pwallet->GetDebit(*this);
586 int64 GetCredit(bool fUseCache=true) const
588 // Must wait until coinbase is safely deep enough in the chain before valuing it
589 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
592 // GetBalance can assume transactions in mapWallet won't change
593 if (fUseCache && fCreditCached)
594 return nCreditCached;
595 nCreditCached = pwallet->GetCredit(*this);
596 fCreditCached = true;
597 return nCreditCached;
600 int64 GetAvailableCredit(bool fUseCache=true) const
602 // Must wait until coinbase is safely deep enough in the chain before valuing it
603 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
606 if (fUseCache && fAvailableCreditCached)
607 return nAvailableCreditCached;
610 for (unsigned int i = 0; i < vout.size(); i++)
614 const CTxOut &txout = vout[i];
615 nCredit += pwallet->GetCredit(txout);
616 if (!MoneyRange(nCredit))
617 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
621 nAvailableCreditCached = nCredit;
622 fAvailableCreditCached = true;
627 int64 GetChange() const
630 return nChangeCached;
631 nChangeCached = pwallet->GetChange(*this);
632 fChangeCached = true;
633 return nChangeCached;
636 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
637 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
639 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
640 int64& nSent, int64& nFee) const;
642 bool IsFromMe() const
644 return (GetDebit() > 0);
647 bool IsTrusted() const
649 // Quick answer in most cases
652 int nDepth = GetDepthInMainChain();
657 if (fConfChange || !IsFromMe()) // using wtx's cached debit
660 // If no confirmations but it's from us, we can still
661 // consider it confirmed if all dependencies are confirmed
662 std::map<uint256, const CMerkleTx*> mapPrev;
663 std::vector<const CMerkleTx*> vWorkQueue;
664 vWorkQueue.reserve(vtxPrev.size()+1);
665 vWorkQueue.push_back(this);
666 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
668 const CMerkleTx* ptx = vWorkQueue[i];
672 int nPDepth = ptx->GetDepthInMainChain();
677 if (!pwallet->IsFromMe(*ptx))
682 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
683 mapPrev[tx.GetHash()] = &tx;
686 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
688 if (!mapPrev.count(txin.prevout.hash))
690 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
698 int64 GetTxTime() const;
699 int GetRequestCount() const;
701 void AddSupportingTransactions();
703 bool AcceptWalletTransaction(bool fCheckInputs=true);
704 void RelayWalletTransaction();
717 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
719 tx = txIn; i = iIn; nDepth = nDepthIn;
722 std::string ToString() const
724 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
729 printf("%s\n", ToString().c_str());
736 /** Private key that includes an expiration date in case it never gets used. */
743 std::string strComment;
744 //// todo: add something to note what created it (user, getnewaddress, change)
745 //// maybe should have a map<string, string> property map
747 CWalletKey(int64 nExpires=0)
749 nTimeCreated = (nExpires ? GetTime() : 0);
750 nTimeExpires = nExpires;
755 if (!(nType & SER_GETHASH))
757 READWRITE(vchPrivKey);
758 READWRITE(nTimeCreated);
759 READWRITE(nTimeExpires);
760 READWRITE(strComment);
769 /** Account information.
770 * Stored in wallet with key "acc"+string account name.
784 vchPubKey = CPubKey();
789 if (!(nType & SER_GETHASH))
791 READWRITE(vchPubKey);
797 /** Internal transfers.
798 * Database key is acentry<account><counter>.
800 class CAccountingEntry
803 std::string strAccount;
806 std::string strOtherAccount;
807 std::string strComment;
809 int64 nOrderPos; // position in ordered transaction list
822 strOtherAccount.clear();
829 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
830 if (!(nType & SER_GETHASH))
832 // Note: strAccount is serialized as part of the key, not here.
833 READWRITE(nCreditDebit);
835 READWRITE(strOtherAccount);
839 WriteOrderPos(nOrderPos, me.mapValue);
841 if (!(mapValue.empty() && _ssExtra.empty()))
843 CDataStream ss(nType, nVersion);
844 ss.insert(ss.begin(), '\0');
846 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
847 me.strComment.append(ss.str());
851 READWRITE(strComment);
853 size_t nSepPos = strComment.find("\0", 0, 1);
857 if (std::string::npos != nSepPos)
859 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
861 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
863 ReadOrderPos(me.nOrderPos, me.mapValue);
865 if (std::string::npos != nSepPos)
866 me.strComment.erase(nSepPos);
868 me.mapValue.erase("n");
872 std::vector<char> _ssExtra;
875 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);