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
19 #include "ui_interface.h"
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
40 /** A key pool entry */
52 CKeyPool(const CPubKey& vchPubKeyIn)
55 vchPubKey = vchPubKeyIn;
60 if (!(nType & SER_GETHASH))
67 /** Address book data */
68 class CAddressBookData
80 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
81 * and provides the ability to create new transactions.
83 class CWallet : public CCryptoKeyStore
86 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
88 CWalletDB *pwalletdbEncryption;
90 // the current wallet version: clients below this version are not able to load the wallet
93 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
94 int nWalletMaxVersion;
100 mutable CCriticalSection cs_wallet;
103 std::string strWalletFile;
105 std::set<int64> setKeyPool;
106 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
108 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
109 MasterKeyMap mapMasterKeys;
110 unsigned int nMasterKeyMaxID;
114 nWalletVersion = FEATURE_BASE;
115 nWalletMaxVersion = FEATURE_BASE;
118 pwalletdbEncryption = NULL;
123 CWallet(std::string strWalletFileIn)
125 nWalletVersion = FEATURE_BASE;
126 nWalletMaxVersion = FEATURE_BASE;
127 strWalletFile = strWalletFileIn;
130 pwalletdbEncryption = NULL;
136 std::map<uint256, CWalletTx> mapWallet;
138 std::map<uint256, int> mapRequestCount;
140 std::map<CTxDestination, CAddressBookData> mapAddressBook;
142 CPubKey vchDefaultKey;
144 std::set<COutPoint> setLockedCoins;
148 // check whether we are allowed to upgrade (or already support) to the named feature
149 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
151 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true) const;
152 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
153 bool IsLockedCoin(uint256 hash, unsigned int n) const;
154 void LockCoin(COutPoint& output);
155 void UnlockCoin(COutPoint& output);
156 void UnlockAllCoins();
157 void ListLockedCoins(std::vector<COutPoint>& vOutpts);
159 // keystore implementation
160 // Generate a new key
161 CPubKey GenerateNewKey();
162 // Adds a key to the store, and saves it to disk.
163 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
164 // Adds a key to the store, without saving it to disk (used by LoadWallet)
165 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
166 // Load metadata (used by LoadWallet)
167 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
169 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
171 // Adds an encrypted key to the store, and saves it to disk.
172 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
173 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
174 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
175 bool AddCScript(const CScript& redeemScript);
176 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
178 bool Unlock(const SecureString& strWalletPassphrase);
179 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
180 bool EncryptWallet(const SecureString& strWalletPassphrase);
182 void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
184 /** Increment the next transaction order id
185 @return next transaction order id
187 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
189 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
190 typedef std::multimap<int64, TxPair > TxItems;
192 /** Get the wallet's activity log
193 @return multimap of ordered transactions and accounting entries
194 @warning Returned pointers are *only* valid within the scope of passed acentries
196 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
199 bool AddToWallet(const CWalletTx& wtxIn);
200 bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
201 bool EraseFromWallet(uint256 hash);
202 void WalletUpdateSpent(const CTransaction& prevout);
203 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
204 void ReacceptWalletTransactions();
205 void ResendWalletTransactions();
206 int64 GetBalance() const;
207 int64 GetUnconfirmedBalance() const;
208 int64 GetImmatureBalance() const;
209 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend,
210 CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason);
211 bool CreateTransaction(CScript scriptPubKey, int64 nValue,
212 CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason);
213 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
214 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
215 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
218 bool TopUpKeyPool(unsigned int kpSize = 0);
219 int64 AddReserveKey(const CKeyPool& keypool);
220 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
221 void KeepKey(int64 nIndex);
222 void ReturnKey(int64 nIndex);
223 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
224 int64 GetOldestKeyPoolTime();
225 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
227 std::set< std::set<CTxDestination> > GetAddressGroupings();
228 std::map<CTxDestination, int64> GetAddressBalances();
230 std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;
232 bool IsMine(const CTxIn& txin) const;
233 int64 GetDebit(const CTxIn& txin) const;
234 bool IsMine(const CTxOut& txout) const
236 return ::IsMine(*this, txout.scriptPubKey);
238 int64 GetCredit(const CTxOut& txout) const
240 if (!MoneyRange(txout.nValue))
241 throw std::runtime_error("CWallet::GetCredit() : value out of range");
242 return (IsMine(txout) ? txout.nValue : 0);
244 bool IsChange(const CTxOut& txout) const;
245 int64 GetChange(const CTxOut& txout) const
247 if (!MoneyRange(txout.nValue))
248 throw std::runtime_error("CWallet::GetChange() : value out of range");
249 return (IsChange(txout) ? txout.nValue : 0);
251 bool IsMine(const CTransaction& tx) const
253 BOOST_FOREACH(const CTxOut& txout, tx.vout)
258 bool IsFromMe(const CTransaction& tx) const
260 return (GetDebit(tx) > 0);
262 int64 GetDebit(const CTransaction& tx) const
265 BOOST_FOREACH(const CTxIn& txin, tx.vin)
267 nDebit += GetDebit(txin);
268 if (!MoneyRange(nDebit))
269 throw std::runtime_error("CWallet::GetDebit() : value out of range");
273 int64 GetCredit(const CTransaction& tx) const
276 BOOST_FOREACH(const CTxOut& txout, tx.vout)
278 nCredit += GetCredit(txout);
279 if (!MoneyRange(nCredit))
280 throw std::runtime_error("CWallet::GetCredit() : value out of range");
284 int64 GetChange(const CTransaction& tx) const
287 BOOST_FOREACH(const CTxOut& txout, tx.vout)
289 nChange += GetChange(txout);
290 if (!MoneyRange(nChange))
291 throw std::runtime_error("CWallet::GetChange() : value out of range");
295 void SetBestChain(const CBlockLocator& loc);
297 DBErrors LoadWallet(bool& fFirstRunRet);
299 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
301 bool DelAddressBook(const CTxDestination& address);
303 void UpdatedTransaction(const uint256 &hashTx);
305 void PrintWallet(const CBlock& block);
307 void Inventory(const uint256 &hash)
311 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
312 if (mi != mapRequestCount.end())
317 unsigned int GetKeyPoolSize()
319 return setKeyPool.size();
322 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
324 bool SetDefaultKey(const CPubKey &vchPubKey);
326 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
327 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
329 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
330 bool SetMaxVersion(int nVersion);
332 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
333 int GetVersion() { return nWalletVersion; }
335 /** Address book entry changed.
336 * @note called with lock cs_wallet held.
338 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
340 /** Wallet transaction added, removed or updated.
341 * @note called with lock cs_wallet held.
343 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
346 /** A key allocated from the key pool. */
354 CReserveKey(CWallet* pwalletIn)
366 bool GetReservedKey(CPubKey &pubkey);
371 typedef std::map<std::string, std::string> mapValue_t;
374 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
376 if (!mapValue.count("n"))
378 nOrderPos = -1; // TODO: calculate elsewhere
381 nOrderPos = atoi64(mapValue["n"].c_str());
385 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
389 mapValue["n"] = i64tostr(nOrderPos);
393 /** A transaction with a bunch of additional info that only the owner cares about.
394 * It includes any unrecorded transactions needed to link it back to the block chain.
396 class CWalletTx : public CMerkleTx
399 const CWallet* pwallet;
402 std::vector<CMerkleTx> vtxPrev;
404 std::vector<std::pair<std::string, std::string> > vOrderForm;
405 unsigned int fTimeReceivedIsTxTime;
406 unsigned int nTimeReceived; // time received by this node
407 unsigned int nTimeSmart;
409 std::string strFromAccount;
410 std::vector<char> vfSpent; // which outputs are already spent
411 int64 nOrderPos; // position in ordered transaction list
414 mutable bool fDebitCached;
415 mutable bool fCreditCached;
416 mutable bool fImmatureCreditCached;
417 mutable bool fAvailableCreditCached;
418 mutable bool fChangeCached;
419 mutable int64 nDebitCached;
420 mutable int64 nCreditCached;
421 mutable int64 nImmatureCreditCached;
422 mutable int64 nAvailableCreditCached;
423 mutable int64 nChangeCached;
430 CWalletTx(const CWallet* pwalletIn)
435 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
440 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
445 void Init(const CWallet* pwalletIn)
451 fTimeReceivedIsTxTime = false;
455 strFromAccount.clear();
457 fDebitCached = false;
458 fCreditCached = false;
459 fImmatureCreditCached = false;
460 fAvailableCreditCached = false;
461 fChangeCached = false;
464 nImmatureCreditCached = 0;
465 nAvailableCreditCached = 0;
472 CWalletTx* pthis = const_cast<CWalletTx*>(this);
479 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
482 BOOST_FOREACH(char f, vfSpent)
484 str += (f ? '1' : '0');
488 pthis->mapValue["spent"] = str;
490 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
493 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
496 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
499 READWRITE(vOrderForm);
500 READWRITE(fTimeReceivedIsTxTime);
501 READWRITE(nTimeReceived);
507 pthis->strFromAccount = pthis->mapValue["fromaccount"];
509 if (mapValue.count("spent"))
510 BOOST_FOREACH(char c, pthis->mapValue["spent"])
511 pthis->vfSpent.push_back(c != '0');
513 pthis->vfSpent.assign(vout.size(), fSpent);
515 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
517 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
520 pthis->mapValue.erase("fromaccount");
521 pthis->mapValue.erase("version");
522 pthis->mapValue.erase("spent");
523 pthis->mapValue.erase("n");
524 pthis->mapValue.erase("timesmart");
527 // marks certain txout's as spent
528 // returns true if any update took place
529 bool UpdateSpent(const std::vector<char>& vfNewSpent)
531 bool fReturn = false;
532 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
534 if (i == vfSpent.size())
537 if (vfNewSpent[i] && !vfSpent[i])
541 fAvailableCreditCached = false;
547 // make sure balances are recalculated
550 fCreditCached = false;
551 fAvailableCreditCached = false;
552 fDebitCached = false;
553 fChangeCached = false;
556 void BindWallet(CWallet *pwalletIn)
562 void MarkSpent(unsigned int nOut)
564 if (nOut >= vout.size())
565 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
566 vfSpent.resize(vout.size());
569 vfSpent[nOut] = true;
570 fAvailableCreditCached = false;
574 bool IsSpent(unsigned int nOut) const
576 if (nOut >= vout.size())
577 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
578 if (nOut >= vfSpent.size())
580 return (!!vfSpent[nOut]);
583 int64 GetDebit() const
589 nDebitCached = pwallet->GetDebit(*this);
594 int64 GetCredit(bool fUseCache=true) const
596 // Must wait until coinbase is safely deep enough in the chain before valuing it
597 if (IsCoinBase() && GetBlocksToMaturity() > 0)
600 // GetBalance can assume transactions in mapWallet won't change
601 if (fUseCache && fCreditCached)
602 return nCreditCached;
603 nCreditCached = pwallet->GetCredit(*this);
604 fCreditCached = true;
605 return nCreditCached;
608 int64 GetImmatureCredit(bool fUseCache=true) const
610 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
612 if (fUseCache && fImmatureCreditCached)
613 return nImmatureCreditCached;
614 nImmatureCreditCached = pwallet->GetCredit(*this);
615 fImmatureCreditCached = true;
616 return nImmatureCreditCached;
622 int64 GetAvailableCredit(bool fUseCache=true) const
624 // Must wait until coinbase is safely deep enough in the chain before valuing it
625 if (IsCoinBase() && GetBlocksToMaturity() > 0)
628 if (fUseCache && fAvailableCreditCached)
629 return nAvailableCreditCached;
632 for (unsigned int i = 0; i < vout.size(); i++)
636 const CTxOut &txout = vout[i];
637 nCredit += pwallet->GetCredit(txout);
638 if (!MoneyRange(nCredit))
639 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
643 nAvailableCreditCached = nCredit;
644 fAvailableCreditCached = true;
649 int64 GetChange() const
652 return nChangeCached;
653 nChangeCached = pwallet->GetChange(*this);
654 fChangeCached = true;
655 return nChangeCached;
658 void GetAmounts(std::list<std::pair<CTxDestination, int64> >& listReceived,
659 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
661 void GetAccountAmounts(const std::string& strAccount, int64& nReceived,
662 int64& nSent, int64& nFee) const;
664 bool IsFromMe() const
666 return (GetDebit() > 0);
669 bool IsConfirmed() const
671 // Quick answer in most cases
672 if (!IsFinalTx(*this))
674 if (GetDepthInMainChain() >= 1)
676 if (!IsFromMe()) // using wtx's cached debit
679 // If no confirmations but it's from us, we can still
680 // consider it confirmed if all dependencies are confirmed
681 std::map<uint256, const CMerkleTx*> mapPrev;
682 std::vector<const CMerkleTx*> vWorkQueue;
683 vWorkQueue.reserve(vtxPrev.size()+1);
684 vWorkQueue.push_back(this);
685 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
687 const CMerkleTx* ptx = vWorkQueue[i];
689 if (!IsFinalTx(*ptx))
691 if (ptx->GetDepthInMainChain() >= 1)
693 if (!pwallet->IsFromMe(*ptx))
698 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
699 mapPrev[tx.GetHash()] = &tx;
702 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
704 if (!mapPrev.count(txin.prevout.hash))
706 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
714 int64 GetTxTime() const;
715 int GetRequestCount() const;
717 void AddSupportingTransactions();
718 bool AcceptWalletTransaction();
719 void RelayWalletTransaction();
732 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
734 tx = txIn; i = iIn; nDepth = nDepthIn;
737 std::string ToString() const
739 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
744 printf("%s\n", ToString().c_str());
751 /** Private key that includes an expiration date in case it never gets used. */
758 std::string strComment;
759 //// todo: add something to note what created it (user, getnewaddress, change)
760 //// maybe should have a map<string, string> property map
762 CWalletKey(int64 nExpires=0)
764 nTimeCreated = (nExpires ? GetTime() : 0);
765 nTimeExpires = nExpires;
770 if (!(nType & SER_GETHASH))
772 READWRITE(vchPrivKey);
773 READWRITE(nTimeCreated);
774 READWRITE(nTimeExpires);
775 READWRITE(strComment);
784 /** Account information.
785 * Stored in wallet with key "acc"+string account name.
799 vchPubKey = CPubKey();
804 if (!(nType & SER_GETHASH))
806 READWRITE(vchPubKey);
812 /** Internal transfers.
813 * Database key is acentry<account><counter>.
815 class CAccountingEntry
818 std::string strAccount;
821 std::string strOtherAccount;
822 std::string strComment;
824 int64 nOrderPos; // position in ordered transaction list
837 strOtherAccount.clear();
844 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
845 if (!(nType & SER_GETHASH))
847 // Note: strAccount is serialized as part of the key, not here.
848 READWRITE(nCreditDebit);
850 READWRITE(strOtherAccount);
854 WriteOrderPos(nOrderPos, me.mapValue);
856 if (!(mapValue.empty() && _ssExtra.empty()))
858 CDataStream ss(nType, nVersion);
859 ss.insert(ss.begin(), '\0');
861 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
862 me.strComment.append(ss.str());
866 READWRITE(strComment);
868 size_t nSepPos = strComment.find("\0", 0, 1);
872 if (std::string::npos != nSepPos)
874 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
876 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
878 ReadOrderPos(me.nOrderPos, me.mapValue);
880 if (std::string::npos != nSepPos)
881 me.strComment.erase(nSepPos);
883 me.mapValue.erase("n");
887 std::vector<char> _ssExtra;
890 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);