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);
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
339 &address, const std::string &label, bool isMine,
340 const std::string &purpose,
341 ChangeType status)> NotifyAddressBookChanged;
343 /** Wallet transaction added, removed or updated.
344 * @note called with lock cs_wallet held.
346 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
347 ChangeType status)> NotifyTransactionChanged;
350 /** A key allocated from the key pool. */
358 CReserveKey(CWallet* pwalletIn)
370 bool GetReservedKey(CPubKey &pubkey);
375 typedef std::map<std::string, std::string> mapValue_t;
378 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
380 if (!mapValue.count("n"))
382 nOrderPos = -1; // TODO: calculate elsewhere
385 nOrderPos = atoi64(mapValue["n"].c_str());
389 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
393 mapValue["n"] = i64tostr(nOrderPos);
397 /** A transaction with a bunch of additional info that only the owner cares about.
398 * It includes any unrecorded transactions needed to link it back to the block chain.
400 class CWalletTx : public CMerkleTx
403 const CWallet* pwallet;
406 std::vector<CMerkleTx> vtxPrev;
408 std::vector<std::pair<std::string, std::string> > vOrderForm;
409 unsigned int fTimeReceivedIsTxTime;
410 unsigned int nTimeReceived; // time received by this node
411 unsigned int nTimeSmart;
413 std::string strFromAccount;
414 std::vector<char> vfSpent; // which outputs are already spent
415 int64 nOrderPos; // position in ordered transaction list
418 mutable bool fDebitCached;
419 mutable bool fCreditCached;
420 mutable bool fImmatureCreditCached;
421 mutable bool fAvailableCreditCached;
422 mutable bool fChangeCached;
423 mutable int64 nDebitCached;
424 mutable int64 nCreditCached;
425 mutable int64 nImmatureCreditCached;
426 mutable int64 nAvailableCreditCached;
427 mutable int64 nChangeCached;
434 CWalletTx(const CWallet* pwalletIn)
439 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
444 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
449 void Init(const CWallet* pwalletIn)
455 fTimeReceivedIsTxTime = false;
459 strFromAccount.clear();
461 fDebitCached = false;
462 fCreditCached = false;
463 fImmatureCreditCached = false;
464 fAvailableCreditCached = false;
465 fChangeCached = false;
468 nImmatureCreditCached = 0;
469 nAvailableCreditCached = 0;
476 CWalletTx* pthis = const_cast<CWalletTx*>(this);
483 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
486 BOOST_FOREACH(char f, vfSpent)
488 str += (f ? '1' : '0');
492 pthis->mapValue["spent"] = str;
494 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
497 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
500 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
503 READWRITE(vOrderForm);
504 READWRITE(fTimeReceivedIsTxTime);
505 READWRITE(nTimeReceived);
511 pthis->strFromAccount = pthis->mapValue["fromaccount"];
513 if (mapValue.count("spent"))
514 BOOST_FOREACH(char c, pthis->mapValue["spent"])
515 pthis->vfSpent.push_back(c != '0');
517 pthis->vfSpent.assign(vout.size(), fSpent);
519 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
521 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
524 pthis->mapValue.erase("fromaccount");
525 pthis->mapValue.erase("version");
526 pthis->mapValue.erase("spent");
527 pthis->mapValue.erase("n");
528 pthis->mapValue.erase("timesmart");
531 // marks certain txout's as spent
532 // returns true if any update took place
533 bool UpdateSpent(const std::vector<char>& vfNewSpent)
535 bool fReturn = false;
536 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
538 if (i == vfSpent.size())
541 if (vfNewSpent[i] && !vfSpent[i])
545 fAvailableCreditCached = false;
551 // make sure balances are recalculated
554 fCreditCached = false;
555 fAvailableCreditCached = false;
556 fDebitCached = false;
557 fChangeCached = false;
560 void BindWallet(CWallet *pwalletIn)
566 void MarkSpent(unsigned int nOut)
568 if (nOut >= vout.size())
569 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
570 vfSpent.resize(vout.size());
573 vfSpent[nOut] = true;
574 fAvailableCreditCached = false;
578 bool IsSpent(unsigned int nOut) const
580 if (nOut >= vout.size())
581 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
582 if (nOut >= vfSpent.size())
584 return (!!vfSpent[nOut]);
587 int64 GetDebit() const
593 nDebitCached = pwallet->GetDebit(*this);
598 int64 GetCredit(bool fUseCache=true) const
600 // Must wait until coinbase is safely deep enough in the chain before valuing it
601 if (IsCoinBase() && GetBlocksToMaturity() > 0)
604 // GetBalance can assume transactions in mapWallet won't change
605 if (fUseCache && fCreditCached)
606 return nCreditCached;
607 nCreditCached = pwallet->GetCredit(*this);
608 fCreditCached = true;
609 return nCreditCached;
612 int64 GetImmatureCredit(bool fUseCache=true) const
614 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
616 if (fUseCache && fImmatureCreditCached)
617 return nImmatureCreditCached;
618 nImmatureCreditCached = pwallet->GetCredit(*this);
619 fImmatureCreditCached = true;
620 return nImmatureCreditCached;
626 int64 GetAvailableCredit(bool fUseCache=true) const
628 // Must wait until coinbase is safely deep enough in the chain before valuing it
629 if (IsCoinBase() && GetBlocksToMaturity() > 0)
632 if (fUseCache && fAvailableCreditCached)
633 return nAvailableCreditCached;
636 for (unsigned int i = 0; i < vout.size(); i++)
640 const CTxOut &txout = vout[i];
641 nCredit += pwallet->GetCredit(txout);
642 if (!MoneyRange(nCredit))
643 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
647 nAvailableCreditCached = nCredit;
648 fAvailableCreditCached = true;
653 int64 GetChange() const
656 return nChangeCached;
657 nChangeCached = pwallet->GetChange(*this);
658 fChangeCached = true;
659 return nChangeCached;
662 void GetAmounts(std::list<std::pair<CTxDestination, int64> >& listReceived,
663 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
665 void GetAccountAmounts(const std::string& strAccount, int64& nReceived,
666 int64& nSent, int64& nFee) const;
668 bool IsFromMe() const
670 return (GetDebit() > 0);
673 bool IsConfirmed() const
675 // Quick answer in most cases
676 if (!IsFinalTx(*this))
678 if (GetDepthInMainChain() >= 1)
680 if (!IsFromMe()) // using wtx's cached debit
683 // If no confirmations but it's from us, we can still
684 // consider it confirmed if all dependencies are confirmed
685 std::map<uint256, const CMerkleTx*> mapPrev;
686 std::vector<const CMerkleTx*> vWorkQueue;
687 vWorkQueue.reserve(vtxPrev.size()+1);
688 vWorkQueue.push_back(this);
689 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
691 const CMerkleTx* ptx = vWorkQueue[i];
693 if (!IsFinalTx(*ptx))
695 if (ptx->GetDepthInMainChain() >= 1)
697 if (!pwallet->IsFromMe(*ptx))
702 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
703 mapPrev[tx.GetHash()] = &tx;
706 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
708 if (!mapPrev.count(txin.prevout.hash))
710 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
718 int64 GetTxTime() const;
719 int GetRequestCount() const;
721 void AddSupportingTransactions();
722 bool AcceptWalletTransaction();
723 void RelayWalletTransaction();
736 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
738 tx = txIn; i = iIn; nDepth = nDepthIn;
741 std::string ToString() const
743 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
748 printf("%s\n", ToString().c_str());
755 /** Private key that includes an expiration date in case it never gets used. */
762 std::string strComment;
763 //// todo: add something to note what created it (user, getnewaddress, change)
764 //// maybe should have a map<string, string> property map
766 CWalletKey(int64 nExpires=0)
768 nTimeCreated = (nExpires ? GetTime() : 0);
769 nTimeExpires = nExpires;
774 if (!(nType & SER_GETHASH))
776 READWRITE(vchPrivKey);
777 READWRITE(nTimeCreated);
778 READWRITE(nTimeExpires);
779 READWRITE(strComment);
788 /** Account information.
789 * Stored in wallet with key "acc"+string account name.
803 vchPubKey = CPubKey();
808 if (!(nType & SER_GETHASH))
810 READWRITE(vchPubKey);
816 /** Internal transfers.
817 * Database key is acentry<account><counter>.
819 class CAccountingEntry
822 std::string strAccount;
825 std::string strOtherAccount;
826 std::string strComment;
828 int64 nOrderPos; // position in ordered transaction list
841 strOtherAccount.clear();
848 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
849 if (!(nType & SER_GETHASH))
851 // Note: strAccount is serialized as part of the key, not here.
852 READWRITE(nCreditDebit);
854 READWRITE(strOtherAccount);
858 WriteOrderPos(nOrderPos, me.mapValue);
860 if (!(mapValue.empty() && _ssExtra.empty()))
862 CDataStream ss(nType, nVersion);
863 ss.insert(ss.begin(), '\0');
865 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
866 me.strComment.append(ss.str());
870 READWRITE(strComment);
872 size_t nSepPos = strComment.find("\0", 0, 1);
876 if (std::string::npos != nSepPos)
878 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
880 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
882 ReadOrderPos(me.nOrderPos, me.mapValue);
884 if (std::string::npos != nSepPos)
885 me.strComment.erase(nSepPos);
887 me.mapValue.erase("n");
891 std::vector<char> _ssExtra;
894 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);