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 void ReacceptWalletTransactions();
179 void ResendWalletTransactions();
180 int64 GetBalance() const;
181 int64 GetUnconfirmedBalance() const;
182 int64 GetImmatureBalance() const;
183 int64 GetStake() const;
184 int64 GetNewMint() const;
185 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
186 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl *coinControl=NULL);
187 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
189 bool GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight);
190 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key);
192 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
193 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
196 bool TopUpKeyPool(unsigned int nSize = 0);
197 int64 AddReserveKey(const CKeyPool& keypool);
198 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
199 void KeepKey(int64 nIndex);
200 void ReturnKey(int64 nIndex);
201 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
202 int64 GetOldestKeyPoolTime();
203 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
205 std::set< std::set<CTxDestination> > GetAddressGroupings();
206 std::map<CTxDestination, int64> GetAddressBalances();
208 bool IsMine(const CTxIn& txin) const;
209 int64 GetDebit(const CTxIn& txin) const;
210 bool IsMine(const CTxOut& txout) const
212 return ::IsMine(*this, txout.scriptPubKey);
214 int64 GetCredit(const CTxOut& txout) const
216 if (!MoneyRange(txout.nValue))
217 throw std::runtime_error("CWallet::GetCredit() : value out of range");
218 return (IsMine(txout) ? txout.nValue : 0);
220 bool IsChange(const CTxOut& txout) const;
221 int64 GetChange(const CTxOut& txout) const
223 if (!MoneyRange(txout.nValue))
224 throw std::runtime_error("CWallet::GetChange() : value out of range");
225 return (IsChange(txout) ? txout.nValue : 0);
227 bool IsMine(const CTransaction& tx) const
229 BOOST_FOREACH(const CTxOut& txout, tx.vout)
230 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
234 bool IsFromMe(const CTransaction& tx) const
236 return (GetDebit(tx) > 0);
238 int64 GetDebit(const CTransaction& tx) const
241 BOOST_FOREACH(const CTxIn& txin, tx.vin)
243 nDebit += GetDebit(txin);
244 if (!MoneyRange(nDebit))
245 throw std::runtime_error("CWallet::GetDebit() : value out of range");
249 int64 GetCredit(const CTransaction& tx) const
252 BOOST_FOREACH(const CTxOut& txout, tx.vout)
254 nCredit += GetCredit(txout);
255 if (!MoneyRange(nCredit))
256 throw std::runtime_error("CWallet::GetCredit() : value out of range");
260 int64 GetChange(const CTransaction& tx) const
263 BOOST_FOREACH(const CTxOut& txout, tx.vout)
265 nChange += GetChange(txout);
266 if (!MoneyRange(nChange))
267 throw std::runtime_error("CWallet::GetChange() : value out of range");
271 void SetBestChain(const CBlockLocator& loc);
273 DBErrors LoadWallet(bool& fFirstRunRet);
275 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
277 bool DelAddressBookName(const CTxDestination& address);
279 void UpdatedTransaction(const uint256 &hashTx);
281 void PrintWallet(const CBlock& block);
283 void Inventory(const uint256 &hash)
287 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
288 if (mi != mapRequestCount.end())
293 unsigned int GetKeyPoolSize()
295 return setKeyPool.size();
298 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
300 bool SetDefaultKey(const CPubKey &vchPubKey);
302 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
303 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
305 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
306 bool SetMaxVersion(int nVersion);
308 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
309 int GetVersion() { return nWalletVersion; }
311 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
312 void DisableTransaction(const CTransaction &tx);
314 /** Address book entry changed.
315 * @note called with lock cs_wallet held.
317 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
319 /** Wallet transaction added, removed or updated.
320 * @note called with lock cs_wallet held.
322 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
325 /** A key allocated from the key pool. */
333 CReserveKey(CWallet* pwalletIn)
346 CPubKey GetReservedKey();
351 typedef std::map<std::string, std::string> mapValue_t;
354 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
356 if (!mapValue.count("n"))
358 nOrderPos = -1; // TODO: calculate elsewhere
361 nOrderPos = atoi64(mapValue["n"].c_str());
365 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
369 mapValue["n"] = i64tostr(nOrderPos);
373 /** A transaction with a bunch of additional info that only the owner cares about.
374 * It includes any unrecorded transactions needed to link it back to the block chain.
376 class CWalletTx : public CMerkleTx
379 const CWallet* pwallet;
382 std::vector<CMerkleTx> vtxPrev;
384 std::vector<std::pair<std::string, std::string> > vOrderForm;
385 unsigned int fTimeReceivedIsTxTime;
386 unsigned int nTimeReceived; // time received by this node
387 unsigned int nTimeSmart;
389 std::string strFromAccount;
390 std::vector<char> vfSpent; // which outputs are already spent
391 int64 nOrderPos; // position in ordered transaction list
394 mutable bool fDebitCached;
395 mutable bool fCreditCached;
396 mutable bool fAvailableCreditCached;
397 mutable bool fChangeCached;
398 mutable int64 nDebitCached;
399 mutable int64 nCreditCached;
400 mutable int64 nAvailableCreditCached;
401 mutable int64 nChangeCached;
408 CWalletTx(const CWallet* pwalletIn)
413 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
418 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
423 void Init(const CWallet* pwalletIn)
429 fTimeReceivedIsTxTime = false;
433 strFromAccount.clear();
435 fDebitCached = false;
436 fCreditCached = false;
437 fAvailableCreditCached = false;
438 fChangeCached = false;
441 nAvailableCreditCached = 0;
448 CWalletTx* pthis = const_cast<CWalletTx*>(this);
455 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
458 BOOST_FOREACH(char f, vfSpent)
460 str += (f ? '1' : '0');
464 pthis->mapValue["spent"] = str;
466 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
469 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
472 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
475 READWRITE(vOrderForm);
476 READWRITE(fTimeReceivedIsTxTime);
477 READWRITE(nTimeReceived);
483 pthis->strFromAccount = pthis->mapValue["fromaccount"];
485 if (mapValue.count("spent"))
486 BOOST_FOREACH(char c, pthis->mapValue["spent"])
487 pthis->vfSpent.push_back(c != '0');
489 pthis->vfSpent.assign(vout.size(), fSpent);
491 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
493 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
496 pthis->mapValue.erase("fromaccount");
497 pthis->mapValue.erase("version");
498 pthis->mapValue.erase("spent");
499 pthis->mapValue.erase("n");
500 pthis->mapValue.erase("timesmart");
503 // marks certain txout's as spent
504 // returns true if any update took place
505 bool UpdateSpent(const std::vector<char>& vfNewSpent)
507 bool fReturn = false;
508 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
510 if (i == vfSpent.size())
513 if (vfNewSpent[i] && !vfSpent[i])
517 fAvailableCreditCached = false;
523 // make sure balances are recalculated
526 fCreditCached = false;
527 fAvailableCreditCached = false;
528 fDebitCached = false;
529 fChangeCached = false;
532 void BindWallet(CWallet *pwalletIn)
538 void MarkSpent(unsigned int nOut)
540 if (nOut >= vout.size())
541 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
542 vfSpent.resize(vout.size());
545 vfSpent[nOut] = true;
546 fAvailableCreditCached = false;
550 void MarkUnspent(unsigned int nOut)
552 if (nOut >= vout.size())
553 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
554 vfSpent.resize(vout.size());
557 vfSpent[nOut] = false;
558 fAvailableCreditCached = false;
562 bool IsSpent(unsigned int nOut) const
564 if (nOut >= vout.size())
565 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
566 if (nOut >= vfSpent.size())
568 return (!!vfSpent[nOut]);
571 int64 GetDebit() const
577 nDebitCached = pwallet->GetDebit(*this);
582 int64 GetCredit(bool fUseCache=true) const
584 // Must wait until coinbase is safely deep enough in the chain before valuing it
585 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
588 // GetBalance can assume transactions in mapWallet won't change
589 if (fUseCache && fCreditCached)
590 return nCreditCached;
591 nCreditCached = pwallet->GetCredit(*this);
592 fCreditCached = true;
593 return nCreditCached;
596 int64 GetAvailableCredit(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 if (fUseCache && fAvailableCreditCached)
603 return nAvailableCreditCached;
606 for (unsigned int i = 0; i < vout.size(); i++)
610 const CTxOut &txout = vout[i];
611 nCredit += pwallet->GetCredit(txout);
612 if (!MoneyRange(nCredit))
613 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
617 nAvailableCreditCached = nCredit;
618 fAvailableCreditCached = true;
623 int64 GetChange() const
626 return nChangeCached;
627 nChangeCached = pwallet->GetChange(*this);
628 fChangeCached = true;
629 return nChangeCached;
632 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
633 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
635 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
636 int64& nSent, int64& nFee) const;
638 bool IsFromMe() const
640 return (GetDebit() > 0);
643 bool IsConfirmed() const
645 // Quick answer in most cases
648 if (GetDepthInMainChain() >= 1)
650 if (!IsFromMe()) // using wtx's cached debit
653 // If no confirmations but it's from us, we can still
654 // consider it confirmed if all dependencies are confirmed
655 std::map<uint256, const CMerkleTx*> mapPrev;
656 std::vector<const CMerkleTx*> vWorkQueue;
657 vWorkQueue.reserve(vtxPrev.size()+1);
658 vWorkQueue.push_back(this);
659 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
661 const CMerkleTx* ptx = vWorkQueue[i];
665 if (ptx->GetDepthInMainChain() >= 1)
667 if (!pwallet->IsFromMe(*ptx))
672 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
673 mapPrev[tx.GetHash()] = &tx;
676 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
678 if (!mapPrev.count(txin.prevout.hash))
680 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
688 int64 GetTxTime() const;
689 int GetRequestCount() const;
691 void AddSupportingTransactions();
693 bool AcceptWalletTransaction(bool fCheckInputs=true);
694 void RelayWalletTransaction();
707 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
709 tx = txIn; i = iIn; nDepth = nDepthIn;
712 std::string ToString() const
714 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
719 printf("%s\n", ToString().c_str());
726 /** Private key that includes an expiration date in case it never gets used. */
733 std::string strComment;
734 //// todo: add something to note what created it (user, getnewaddress, change)
735 //// maybe should have a map<string, string> property map
737 CWalletKey(int64 nExpires=0)
739 nTimeCreated = (nExpires ? GetTime() : 0);
740 nTimeExpires = nExpires;
745 if (!(nType & SER_GETHASH))
747 READWRITE(vchPrivKey);
748 READWRITE(nTimeCreated);
749 READWRITE(nTimeExpires);
750 READWRITE(strComment);
759 /** Account information.
760 * Stored in wallet with key "acc"+string account name.
774 vchPubKey = CPubKey();
779 if (!(nType & SER_GETHASH))
781 READWRITE(vchPubKey);
787 /** Internal transfers.
788 * Database key is acentry<account><counter>.
790 class CAccountingEntry
793 std::string strAccount;
796 std::string strOtherAccount;
797 std::string strComment;
799 int64 nOrderPos; // position in ordered transaction list
812 strOtherAccount.clear();
819 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
820 if (!(nType & SER_GETHASH))
822 // Note: strAccount is serialized as part of the key, not here.
823 READWRITE(nCreditDebit);
825 READWRITE(strOtherAccount);
829 WriteOrderPos(nOrderPos, me.mapValue);
831 if (!(mapValue.empty() && _ssExtra.empty()))
833 CDataStream ss(nType, nVersion);
834 ss.insert(ss.begin(), '\0');
836 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
837 me.strComment.append(ss.str());
841 READWRITE(strComment);
843 size_t nSepPos = strComment.find("\0", 0, 1);
847 if (std::string::npos != nSepPos)
849 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
851 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
853 ReadOrderPos(me.nOrderPos, me.mapValue);
855 if (std::string::npos != nSepPos)
856 me.strComment.erase(nSepPos);
858 me.mapValue.erase("n");
862 std::vector<char> _ssExtra;
865 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);