1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 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, public CWalletInterface
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 void SyncTransaction(const uint256 &hash, const CTransaction& tx, const CBlock* pblock);
201 bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate);
202 void EraseFromWallet(const uint256 &hash);
203 void WalletUpdateSpent(const CTransaction& prevout);
204 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
205 void ReacceptWalletTransactions();
206 void ResendWalletTransactions();
207 int64 GetBalance() const;
208 int64 GetUnconfirmedBalance() const;
209 int64 GetImmatureBalance() const;
210 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend,
211 CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason);
212 bool CreateTransaction(CScript scriptPubKey, int64 nValue,
213 CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason);
214 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
215 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
216 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
219 bool TopUpKeyPool(unsigned int kpSize = 0);
220 int64 AddReserveKey(const CKeyPool& keypool);
221 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
222 void KeepKey(int64 nIndex);
223 void ReturnKey(int64 nIndex);
224 bool GetKeyFromPool(CPubKey &key);
225 int64 GetOldestKeyPoolTime();
226 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
228 std::set< std::set<CTxDestination> > GetAddressGroupings();
229 std::map<CTxDestination, int64> GetAddressBalances();
231 std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;
233 bool IsMine(const CTxIn& txin) const;
234 int64 GetDebit(const CTxIn& txin) const;
235 bool IsMine(const CTxOut& txout) const
237 return ::IsMine(*this, txout.scriptPubKey);
239 int64 GetCredit(const CTxOut& txout) const
241 if (!MoneyRange(txout.nValue))
242 throw std::runtime_error("CWallet::GetCredit() : value out of range");
243 return (IsMine(txout) ? txout.nValue : 0);
245 bool IsChange(const CTxOut& txout) const;
246 int64 GetChange(const CTxOut& txout) const
248 if (!MoneyRange(txout.nValue))
249 throw std::runtime_error("CWallet::GetChange() : value out of range");
250 return (IsChange(txout) ? txout.nValue : 0);
252 bool IsMine(const CTransaction& tx) const
254 BOOST_FOREACH(const CTxOut& txout, tx.vout)
259 bool IsFromMe(const CTransaction& tx) const
261 return (GetDebit(tx) > 0);
263 int64 GetDebit(const CTransaction& tx) const
266 BOOST_FOREACH(const CTxIn& txin, tx.vin)
268 nDebit += GetDebit(txin);
269 if (!MoneyRange(nDebit))
270 throw std::runtime_error("CWallet::GetDebit() : value out of range");
274 int64 GetCredit(const CTransaction& tx) const
277 BOOST_FOREACH(const CTxOut& txout, tx.vout)
279 nCredit += GetCredit(txout);
280 if (!MoneyRange(nCredit))
281 throw std::runtime_error("CWallet::GetCredit() : value out of range");
285 int64 GetChange(const CTransaction& tx) const
288 BOOST_FOREACH(const CTxOut& txout, tx.vout)
290 nChange += GetChange(txout);
291 if (!MoneyRange(nChange))
292 throw std::runtime_error("CWallet::GetChange() : value out of range");
296 void SetBestChain(const CBlockLocator& loc);
298 DBErrors LoadWallet(bool& fFirstRunRet);
300 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
302 bool DelAddressBook(const CTxDestination& address);
304 void UpdatedTransaction(const uint256 &hashTx);
306 void Inventory(const uint256 &hash)
310 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
311 if (mi != mapRequestCount.end())
316 unsigned int GetKeyPoolSize()
318 return setKeyPool.size();
321 bool SetDefaultKey(const CPubKey &vchPubKey);
323 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
324 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
326 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
327 bool SetMaxVersion(int nVersion);
329 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
330 int GetVersion() { return nWalletVersion; }
332 /** Address book entry changed.
333 * @note called with lock cs_wallet held.
335 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
336 &address, const std::string &label, bool isMine,
337 const std::string &purpose,
338 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,
344 ChangeType status)> NotifyTransactionChanged;
347 /** A key allocated from the key pool. */
355 CReserveKey(CWallet* pwalletIn)
367 bool GetReservedKey(CPubKey &pubkey);
372 typedef std::map<std::string, std::string> mapValue_t;
375 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
377 if (!mapValue.count("n"))
379 nOrderPos = -1; // TODO: calculate elsewhere
382 nOrderPos = atoi64(mapValue["n"].c_str());
386 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
390 mapValue["n"] = i64tostr(nOrderPos);
394 /** A transaction with a bunch of additional info that only the owner cares about.
395 * It includes any unrecorded transactions needed to link it back to the block chain.
397 class CWalletTx : public CMerkleTx
400 const CWallet* pwallet;
403 std::vector<CMerkleTx> vtxPrev;
405 std::vector<std::pair<std::string, std::string> > vOrderForm;
406 unsigned int fTimeReceivedIsTxTime;
407 unsigned int nTimeReceived; // time received by this node
408 unsigned int nTimeSmart;
410 std::string strFromAccount;
411 std::vector<char> vfSpent; // which outputs are already spent
412 int64 nOrderPos; // position in ordered transaction list
415 mutable bool fDebitCached;
416 mutable bool fCreditCached;
417 mutable bool fImmatureCreditCached;
418 mutable bool fAvailableCreditCached;
419 mutable bool fChangeCached;
420 mutable int64 nDebitCached;
421 mutable int64 nCreditCached;
422 mutable int64 nImmatureCreditCached;
423 mutable int64 nAvailableCreditCached;
424 mutable int64 nChangeCached;
431 CWalletTx(const CWallet* pwalletIn)
436 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
441 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
446 void Init(const CWallet* pwalletIn)
452 fTimeReceivedIsTxTime = false;
456 strFromAccount.clear();
458 fDebitCached = false;
459 fCreditCached = false;
460 fImmatureCreditCached = false;
461 fAvailableCreditCached = false;
462 fChangeCached = false;
465 nImmatureCreditCached = 0;
466 nAvailableCreditCached = 0;
473 CWalletTx* pthis = const_cast<CWalletTx*>(this);
480 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
483 BOOST_FOREACH(char f, vfSpent)
485 str += (f ? '1' : '0');
489 pthis->mapValue["spent"] = str;
491 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
494 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
497 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
500 READWRITE(vOrderForm);
501 READWRITE(fTimeReceivedIsTxTime);
502 READWRITE(nTimeReceived);
508 pthis->strFromAccount = pthis->mapValue["fromaccount"];
510 if (mapValue.count("spent"))
511 BOOST_FOREACH(char c, pthis->mapValue["spent"])
512 pthis->vfSpent.push_back(c != '0');
514 pthis->vfSpent.assign(vout.size(), fSpent);
516 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
518 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
521 pthis->mapValue.erase("fromaccount");
522 pthis->mapValue.erase("version");
523 pthis->mapValue.erase("spent");
524 pthis->mapValue.erase("n");
525 pthis->mapValue.erase("timesmart");
528 // marks certain txout's as spent
529 // returns true if any update took place
530 bool UpdateSpent(const std::vector<char>& vfNewSpent)
532 bool fReturn = false;
533 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
535 if (i == vfSpent.size())
538 if (vfNewSpent[i] && !vfSpent[i])
542 fAvailableCreditCached = false;
548 // make sure balances are recalculated
551 fCreditCached = false;
552 fAvailableCreditCached = false;
553 fDebitCached = false;
554 fChangeCached = false;
557 void BindWallet(CWallet *pwalletIn)
563 void MarkSpent(unsigned int nOut)
565 if (nOut >= vout.size())
566 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
567 vfSpent.resize(vout.size());
570 vfSpent[nOut] = true;
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() && 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 GetImmatureCredit(bool fUseCache=true) const
611 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
613 if (fUseCache && fImmatureCreditCached)
614 return nImmatureCreditCached;
615 nImmatureCreditCached = pwallet->GetCredit(*this);
616 fImmatureCreditCached = true;
617 return nImmatureCreditCached;
623 int64 GetAvailableCredit(bool fUseCache=true) const
625 // Must wait until coinbase is safely deep enough in the chain before valuing it
626 if (IsCoinBase() && GetBlocksToMaturity() > 0)
629 if (fUseCache && fAvailableCreditCached)
630 return nAvailableCreditCached;
633 for (unsigned int i = 0; i < vout.size(); i++)
637 const CTxOut &txout = vout[i];
638 nCredit += pwallet->GetCredit(txout);
639 if (!MoneyRange(nCredit))
640 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
644 nAvailableCreditCached = nCredit;
645 fAvailableCreditCached = true;
650 int64 GetChange() const
653 return nChangeCached;
654 nChangeCached = pwallet->GetChange(*this);
655 fChangeCached = true;
656 return nChangeCached;
659 void GetAmounts(std::list<std::pair<CTxDestination, int64> >& listReceived,
660 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
662 void GetAccountAmounts(const std::string& strAccount, int64& nReceived,
663 int64& nSent, int64& nFee) const;
665 bool IsFromMe() const
667 return (GetDebit() > 0);
670 bool IsConfirmed() const
672 // Quick answer in most cases
673 if (!IsFinalTx(*this))
675 if (GetDepthInMainChain() >= 1)
677 if (!IsFromMe()) // using wtx's cached debit
680 // If no confirmations but it's from us, we can still
681 // consider it confirmed if all dependencies are confirmed
682 std::map<uint256, const CMerkleTx*> mapPrev;
683 std::vector<const CMerkleTx*> vWorkQueue;
684 vWorkQueue.reserve(vtxPrev.size()+1);
685 vWorkQueue.push_back(this);
686 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
688 const CMerkleTx* ptx = vWorkQueue[i];
690 if (!IsFinalTx(*ptx))
692 if (ptx->GetDepthInMainChain() >= 1)
694 if (!pwallet->IsFromMe(*ptx))
699 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
700 mapPrev[tx.GetHash()] = &tx;
703 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
705 if (!mapPrev.count(txin.prevout.hash))
707 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
715 int64 GetTxTime() const;
716 int GetRequestCount() const;
718 void AddSupportingTransactions();
719 bool AcceptWalletTransaction();
720 void RelayWalletTransaction();
733 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
735 tx = txIn; i = iIn; nDepth = nDepthIn;
738 std::string ToString() const
740 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
745 LogPrintf("%s\n", ToString().c_str());
752 /** Private key that includes an expiration date in case it never gets used. */
759 std::string strComment;
760 //// todo: add something to note what created it (user, getnewaddress, change)
761 //// maybe should have a map<string, string> property map
763 CWalletKey(int64 nExpires=0)
765 nTimeCreated = (nExpires ? GetTime() : 0);
766 nTimeExpires = nExpires;
771 if (!(nType & SER_GETHASH))
773 READWRITE(vchPrivKey);
774 READWRITE(nTimeCreated);
775 READWRITE(nTimeExpires);
776 READWRITE(strComment);
785 /** Account information.
786 * Stored in wallet with key "acc"+string account name.
800 vchPubKey = CPubKey();
805 if (!(nType & SER_GETHASH))
807 READWRITE(vchPubKey);
813 /** Internal transfers.
814 * Database key is acentry<account><counter>.
816 class CAccountingEntry
819 std::string strAccount;
822 std::string strOtherAccount;
823 std::string strComment;
825 int64 nOrderPos; // position in ordered transaction list
838 strOtherAccount.clear();
845 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
846 if (!(nType & SER_GETHASH))
848 // Note: strAccount is serialized as part of the key, not here.
849 READWRITE(nCreditDebit);
851 READWRITE(strOtherAccount);
855 WriteOrderPos(nOrderPos, me.mapValue);
857 if (!(mapValue.empty() && _ssExtra.empty()))
859 CDataStream ss(nType, nVersion);
860 ss.insert(ss.begin(), '\0');
862 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
863 me.strComment.append(ss.str());
867 READWRITE(strComment);
869 size_t nSepPos = strComment.find("\0", 0, 1);
873 if (std::string::npos != nSepPos)
875 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
877 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
879 ReadOrderPos(me.nOrderPos, me.mapValue);
881 if (std::string::npos != nSepPos)
882 me.strComment.erase(nSepPos);
884 me.mapValue.erase("n");
888 std::vector<char> _ssExtra;