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 bool Unlock(const SecureString& strWalletPassphrase);
153 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
154 bool EncryptWallet(const SecureString& strWalletPassphrase);
156 void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
159 /** Increment the next transaction order id
160 @return next transaction order id
162 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
164 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
165 typedef std::multimap<int64, TxPair > TxItems;
167 /** Get the wallet's activity log
168 @return multimap of ordered transactions and accounting entries
169 @warning Returned pointers are *only* valid within the scope of passed acentries
171 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
174 bool AddToWallet(const CWalletTx& wtxIn);
175 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
176 bool EraseFromWallet(uint256 hash);
177 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
178 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
179 int ScanForWalletTransaction(const uint256& hashTx);
180 void ReacceptWalletTransactions();
181 void ResendWalletTransactions();
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 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
279 bool DelAddressBookName(const CTxDestination& address);
281 void UpdatedTransaction(const uint256 &hashTx);
283 void PrintWallet(const CBlock& block);
285 void Inventory(const uint256 &hash)
289 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
290 if (mi != mapRequestCount.end())
295 unsigned int GetKeyPoolSize()
297 return setKeyPool.size();
300 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
302 bool SetDefaultKey(const CPubKey &vchPubKey);
304 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
305 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
307 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
308 bool SetMaxVersion(int nVersion);
310 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
311 int GetVersion() { return nWalletVersion; }
313 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
314 void DisableTransaction(const CTransaction &tx);
316 /** Address book entry changed.
317 * @note called with lock cs_wallet held.
319 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
321 /** Wallet transaction added, removed or updated.
322 * @note called with lock cs_wallet held.
324 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
327 /** A key allocated from the key pool. */
335 CReserveKey(CWallet* pwalletIn)
348 CPubKey GetReservedKey();
353 typedef std::map<std::string, std::string> mapValue_t;
356 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
358 if (!mapValue.count("n"))
360 nOrderPos = -1; // TODO: calculate elsewhere
363 nOrderPos = atoi64(mapValue["n"].c_str());
367 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
371 mapValue["n"] = i64tostr(nOrderPos);
375 /** A transaction with a bunch of additional info that only the owner cares about.
376 * It includes any unrecorded transactions needed to link it back to the block chain.
378 class CWalletTx : public CMerkleTx
381 const CWallet* pwallet;
384 std::vector<CMerkleTx> vtxPrev;
386 std::vector<std::pair<std::string, std::string> > vOrderForm;
387 unsigned int fTimeReceivedIsTxTime;
388 unsigned int nTimeReceived; // time received by this node
389 unsigned int nTimeSmart;
391 std::string strFromAccount;
392 std::vector<char> vfSpent; // which outputs are already spent
393 int64 nOrderPos; // position in ordered transaction list
396 mutable bool fDebitCached;
397 mutable bool fCreditCached;
398 mutable bool fAvailableCreditCached;
399 mutable bool fChangeCached;
400 mutable int64 nDebitCached;
401 mutable int64 nCreditCached;
402 mutable int64 nAvailableCreditCached;
403 mutable int64 nChangeCached;
410 CWalletTx(const CWallet* pwalletIn)
415 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
420 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
425 void Init(const CWallet* pwalletIn)
431 fTimeReceivedIsTxTime = false;
435 strFromAccount.clear();
437 fDebitCached = false;
438 fCreditCached = false;
439 fAvailableCreditCached = false;
440 fChangeCached = false;
443 nAvailableCreditCached = 0;
450 CWalletTx* pthis = const_cast<CWalletTx*>(this);
457 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
460 BOOST_FOREACH(char f, vfSpent)
462 str += (f ? '1' : '0');
466 pthis->mapValue["spent"] = str;
468 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
471 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
474 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
477 READWRITE(vOrderForm);
478 READWRITE(fTimeReceivedIsTxTime);
479 READWRITE(nTimeReceived);
485 pthis->strFromAccount = pthis->mapValue["fromaccount"];
487 if (mapValue.count("spent"))
488 BOOST_FOREACH(char c, pthis->mapValue["spent"])
489 pthis->vfSpent.push_back(c != '0');
491 pthis->vfSpent.assign(vout.size(), fSpent);
493 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
495 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
498 pthis->mapValue.erase("fromaccount");
499 pthis->mapValue.erase("version");
500 pthis->mapValue.erase("spent");
501 pthis->mapValue.erase("n");
502 pthis->mapValue.erase("timesmart");
505 // marks certain txout's as spent
506 // returns true if any update took place
507 bool UpdateSpent(const std::vector<char>& vfNewSpent)
509 bool fReturn = false;
510 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
512 if (i == vfSpent.size())
515 if (vfNewSpent[i] && !vfSpent[i])
519 fAvailableCreditCached = false;
525 // make sure balances are recalculated
528 fCreditCached = false;
529 fAvailableCreditCached = false;
530 fDebitCached = false;
531 fChangeCached = false;
534 void BindWallet(CWallet *pwalletIn)
540 void MarkSpent(unsigned int nOut)
542 if (nOut >= vout.size())
543 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
544 vfSpent.resize(vout.size());
547 vfSpent[nOut] = true;
548 fAvailableCreditCached = false;
552 void MarkUnspent(unsigned int nOut)
554 if (nOut >= vout.size())
555 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
556 vfSpent.resize(vout.size());
559 vfSpent[nOut] = false;
560 fAvailableCreditCached = false;
564 bool IsSpent(unsigned int nOut) const
566 if (nOut >= vout.size())
567 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
568 if (nOut >= vfSpent.size())
570 return (!!vfSpent[nOut]);
573 int64 GetDebit() const
579 nDebitCached = pwallet->GetDebit(*this);
584 int64 GetCredit(bool fUseCache=true) const
586 // Must wait until coinbase is safely deep enough in the chain before valuing it
587 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
590 // GetBalance can assume transactions in mapWallet won't change
591 if (fUseCache && fCreditCached)
592 return nCreditCached;
593 nCreditCached = pwallet->GetCredit(*this);
594 fCreditCached = true;
595 return nCreditCached;
598 int64 GetAvailableCredit(bool fUseCache=true) const
600 // Must wait until coinbase is safely deep enough in the chain before valuing it
601 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
604 if (fUseCache && fAvailableCreditCached)
605 return nAvailableCreditCached;
608 for (unsigned int i = 0; i < vout.size(); i++)
612 const CTxOut &txout = vout[i];
613 nCredit += pwallet->GetCredit(txout);
614 if (!MoneyRange(nCredit))
615 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
619 nAvailableCreditCached = nCredit;
620 fAvailableCreditCached = true;
625 int64 GetChange() const
628 return nChangeCached;
629 nChangeCached = pwallet->GetChange(*this);
630 fChangeCached = true;
631 return nChangeCached;
634 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
635 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
637 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
638 int64& nSent, int64& nFee) const;
640 bool IsFromMe() const
642 return (GetDebit() > 0);
645 bool IsTrusted() const
647 // Quick answer in most cases
650 if (GetDepthInMainChain() >= 1)
652 if (fConfChange || !IsFromMe()) // using wtx's cached debit
655 // If no confirmations but it's from us, we can still
656 // consider it confirmed if all dependencies are confirmed
657 std::map<uint256, const CMerkleTx*> mapPrev;
658 std::vector<const CMerkleTx*> vWorkQueue;
659 vWorkQueue.reserve(vtxPrev.size()+1);
660 vWorkQueue.push_back(this);
661 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
663 const CMerkleTx* ptx = vWorkQueue[i];
667 if (ptx->GetDepthInMainChain() >= 1)
669 if (!pwallet->IsFromMe(*ptx))
674 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
675 mapPrev[tx.GetHash()] = &tx;
678 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
680 if (!mapPrev.count(txin.prevout.hash))
682 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
691 int64 GetTxTime() const;
692 int GetRequestCount() const;
694 void AddSupportingTransactions(CTxDB& txdb);
696 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
697 bool AcceptWalletTransaction();
699 void RelayWalletTransaction(CTxDB& txdb);
700 void RelayWalletTransaction();
713 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
715 tx = txIn; i = iIn; nDepth = nDepthIn;
718 std::string ToString() const
720 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
725 printf("%s\n", ToString().c_str());
732 /** Private key that includes an expiration date in case it never gets used. */
739 std::string strComment;
740 //// todo: add something to note what created it (user, getnewaddress, change)
741 //// maybe should have a map<string, string> property map
743 CWalletKey(int64 nExpires=0)
745 nTimeCreated = (nExpires ? GetTime() : 0);
746 nTimeExpires = nExpires;
751 if (!(nType & SER_GETHASH))
753 READWRITE(vchPrivKey);
754 READWRITE(nTimeCreated);
755 READWRITE(nTimeExpires);
756 READWRITE(strComment);
765 /** Account information.
766 * Stored in wallet with key "acc"+string account name.
780 vchPubKey = CPubKey();
785 if (!(nType & SER_GETHASH))
787 READWRITE(vchPubKey);
793 /** Internal transfers.
794 * Database key is acentry<account><counter>.
796 class CAccountingEntry
799 std::string strAccount;
802 std::string strOtherAccount;
803 std::string strComment;
805 int64 nOrderPos; // position in ordered transaction list
818 strOtherAccount.clear();
825 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
826 if (!(nType & SER_GETHASH))
828 // Note: strAccount is serialized as part of the key, not here.
829 READWRITE(nCreditDebit);
831 READWRITE(strOtherAccount);
835 WriteOrderPos(nOrderPos, me.mapValue);
837 if (!(mapValue.empty() && _ssExtra.empty()))
839 CDataStream ss(nType, nVersion);
840 ss.insert(ss.begin(), '\0');
842 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
843 me.strComment.append(ss.str());
847 READWRITE(strComment);
849 size_t nSepPos = strComment.find("\0", 0, 1);
853 if (std::string::npos != nSepPos)
855 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
857 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
859 ReadOrderPos(me.nOrderPos, me.mapValue);
861 if (std::string::npos != nSepPos)
862 me.strComment.erase(nSepPos);
864 me.mapValue.erase("n");
868 std::vector<char> _ssExtra;
871 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);