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;
27 /** (client) version numbers for particular wallet features */
30 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
32 FEATURE_WALLETCRYPT = 40000, // wallet encryption
33 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
35 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 SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
74 CWalletDB *pwalletdbEncryption;
76 // the current wallet version: clients below this version are not able to load the wallet
79 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
80 int nWalletMaxVersion;
83 mutable CCriticalSection cs_wallet;
86 std::string strWalletFile;
88 std::set<int64> setKeyPool;
91 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
92 MasterKeyMap mapMasterKeys;
93 unsigned int nMasterKeyMaxID;
97 nWalletVersion = FEATURE_BASE;
98 nWalletMaxVersion = FEATURE_BASE;
101 pwalletdbEncryption = NULL;
104 CWallet(std::string strWalletFileIn)
106 nWalletVersion = FEATURE_BASE;
107 nWalletMaxVersion = FEATURE_BASE;
108 strWalletFile = strWalletFileIn;
111 pwalletdbEncryption = NULL;
115 std::map<uint256, CWalletTx> mapWallet;
117 std::map<uint256, int> mapRequestCount;
119 std::map<CTxDestination, std::string> mapAddressBook;
121 CPubKey vchDefaultKey;
123 // check whether we are allowed to upgrade (or already support) to the named feature
124 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
126 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true) const;
127 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;
128 // keystore implementation
129 // Generate a new key
130 CPubKey GenerateNewKey();
131 // Adds a key to the store, and saves it to disk.
132 bool AddKey(const CKey& key);
133 // Adds a key to the store, without saving it to disk (used by LoadWallet)
134 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
136 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
138 // Adds an encrypted key to the store, and saves it to disk.
139 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
140 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
141 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
142 bool AddCScript(const CScript& redeemScript);
143 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
145 bool Unlock(const SecureString& strWalletPassphrase);
146 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
147 bool EncryptWallet(const SecureString& strWalletPassphrase);
149 /** Increment the next transaction order id
150 @return next transaction order id
152 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
154 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
155 typedef std::multimap<int64, TxPair > TxItems;
157 /** Get the wallet's activity log
158 @return multimap of ordered transactions and accounting entries
159 @warning Returned pointers are *only* valid within the scope of passed acentries
161 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
164 bool AddToWallet(const CWalletTx& wtxIn);
165 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
166 bool EraseFromWallet(uint256 hash);
167 void WalletUpdateSpent(const CTransaction& prevout);
168 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
169 int ScanForWalletTransaction(const uint256& hashTx);
170 void ReacceptWalletTransactions();
171 void ResendWalletTransactions();
172 int64 GetBalance() const;
173 int64 GetUnconfirmedBalance() const;
174 int64 GetImmatureBalance() const;
175 int64 GetStake() const;
176 int64 GetNewMint() const;
177 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
178 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
179 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
180 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew);
181 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
182 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
186 int64 AddReserveKey(const CKeyPool& keypool);
187 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
188 void KeepKey(int64 nIndex);
189 void ReturnKey(int64 nIndex);
190 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
191 int64 GetOldestKeyPoolTime();
192 void GetAllReserveKeys(std::set<CKeyID>& setAddress);
194 std::set< std::set<CTxDestination> > GetAddressGroupings();
195 std::map<CTxDestination, int64> GetAddressBalances();
197 bool IsMine(const CTxIn& txin) const;
198 int64 GetDebit(const CTxIn& txin) const;
199 bool IsMine(const CTxOut& txout) const
201 return ::IsMine(*this, txout.scriptPubKey);
203 int64 GetCredit(const CTxOut& txout) const
205 if (!MoneyRange(txout.nValue))
206 throw std::runtime_error("CWallet::GetCredit() : value out of range");
207 return (IsMine(txout) ? txout.nValue : 0);
209 bool IsChange(const CTxOut& txout) const;
210 int64 GetChange(const CTxOut& txout) const
212 if (!MoneyRange(txout.nValue))
213 throw std::runtime_error("CWallet::GetChange() : value out of range");
214 return (IsChange(txout) ? txout.nValue : 0);
216 bool IsMine(const CTransaction& tx) const
218 BOOST_FOREACH(const CTxOut& txout, tx.vout)
223 bool IsFromMe(const CTransaction& tx) const
225 return (GetDebit(tx) > 0);
227 int64 GetDebit(const CTransaction& tx) const
230 BOOST_FOREACH(const CTxIn& txin, tx.vin)
232 nDebit += GetDebit(txin);
233 if (!MoneyRange(nDebit))
234 throw std::runtime_error("CWallet::GetDebit() : value out of range");
238 int64 GetCredit(const CTransaction& tx) const
241 BOOST_FOREACH(const CTxOut& txout, tx.vout)
243 nCredit += GetCredit(txout);
244 if (!MoneyRange(nCredit))
245 throw std::runtime_error("CWallet::GetCredit() : value out of range");
249 int64 GetChange(const CTransaction& tx) const
252 BOOST_FOREACH(const CTxOut& txout, tx.vout)
254 nChange += GetChange(txout);
255 if (!MoneyRange(nChange))
256 throw std::runtime_error("CWallet::GetChange() : value out of range");
260 void SetBestChain(const CBlockLocator& loc);
262 DBErrors LoadWallet(bool& fFirstRunRet);
264 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
266 bool DelAddressBookName(const CTxDestination& address);
268 void UpdatedTransaction(const uint256 &hashTx);
270 void PrintWallet(const CBlock& block);
272 void Inventory(const uint256 &hash)
276 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
277 if (mi != mapRequestCount.end())
284 return setKeyPool.size();
287 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
289 bool SetDefaultKey(const CPubKey &vchPubKey);
291 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
292 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
294 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
295 bool SetMaxVersion(int nVersion);
297 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
298 int GetVersion() { return nWalletVersion; }
300 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
301 void DisableTransaction(const CTransaction &tx);
303 /** Address book entry changed.
304 * @note called with lock cs_wallet held.
306 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
308 /** Wallet transaction added, removed or updated.
309 * @note called with lock cs_wallet held.
311 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
314 /** A key allocated from the key pool. */
322 CReserveKey(CWallet* pwalletIn)
335 CPubKey GetReservedKey();
340 typedef std::map<std::string, std::string> mapValue_t;
343 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
345 if (!mapValue.count("n"))
347 nOrderPos = -1; // TODO: calculate elsewhere
350 nOrderPos = atoi64(mapValue["n"].c_str());
354 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
358 mapValue["n"] = i64tostr(nOrderPos);
362 /** A transaction with a bunch of additional info that only the owner cares about.
363 * It includes any unrecorded transactions needed to link it back to the block chain.
365 class CWalletTx : public CMerkleTx
368 const CWallet* pwallet;
371 std::vector<CMerkleTx> vtxPrev;
373 std::vector<std::pair<std::string, std::string> > vOrderForm;
374 unsigned int fTimeReceivedIsTxTime;
375 unsigned int nTimeReceived; // time received by this node
376 unsigned int nTimeSmart;
378 std::string strFromAccount;
379 std::vector<char> vfSpent; // which outputs are already spent
380 int64 nOrderPos; // position in ordered transaction list
383 mutable bool fDebitCached;
384 mutable bool fCreditCached;
385 mutable bool fAvailableCreditCached;
386 mutable bool fChangeCached;
387 mutable int64 nDebitCached;
388 mutable int64 nCreditCached;
389 mutable int64 nAvailableCreditCached;
390 mutable int64 nChangeCached;
397 CWalletTx(const CWallet* pwalletIn)
402 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
407 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
412 void Init(const CWallet* pwalletIn)
418 fTimeReceivedIsTxTime = false;
422 strFromAccount.clear();
424 fDebitCached = false;
425 fCreditCached = false;
426 fAvailableCreditCached = false;
427 fChangeCached = false;
430 nAvailableCreditCached = 0;
437 CWalletTx* pthis = const_cast<CWalletTx*>(this);
444 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
447 BOOST_FOREACH(char f, vfSpent)
449 str += (f ? '1' : '0');
453 pthis->mapValue["spent"] = str;
455 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
458 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
461 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
464 READWRITE(vOrderForm);
465 READWRITE(fTimeReceivedIsTxTime);
466 READWRITE(nTimeReceived);
472 pthis->strFromAccount = pthis->mapValue["fromaccount"];
474 if (mapValue.count("spent"))
475 BOOST_FOREACH(char c, pthis->mapValue["spent"])
476 pthis->vfSpent.push_back(c != '0');
478 pthis->vfSpent.assign(vout.size(), fSpent);
480 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
482 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
485 pthis->mapValue.erase("fromaccount");
486 pthis->mapValue.erase("version");
487 pthis->mapValue.erase("spent");
488 pthis->mapValue.erase("n");
489 pthis->mapValue.erase("timesmart");
492 // marks certain txout's as spent
493 // returns true if any update took place
494 bool UpdateSpent(const std::vector<char>& vfNewSpent)
496 bool fReturn = false;
497 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
499 if (i == vfSpent.size())
502 if (vfNewSpent[i] && !vfSpent[i])
506 fAvailableCreditCached = false;
512 // make sure balances are recalculated
515 fCreditCached = false;
516 fAvailableCreditCached = false;
517 fDebitCached = false;
518 fChangeCached = false;
521 void BindWallet(CWallet *pwalletIn)
527 void MarkSpent(unsigned int nOut)
529 if (nOut >= vout.size())
530 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
531 vfSpent.resize(vout.size());
534 vfSpent[nOut] = true;
535 fAvailableCreditCached = false;
539 void MarkUnspent(unsigned int nOut)
541 if (nOut >= vout.size())
542 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
543 vfSpent.resize(vout.size());
546 vfSpent[nOut] = false;
547 fAvailableCreditCached = false;
551 bool IsSpent(unsigned int nOut) const
553 if (nOut >= vout.size())
554 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
555 if (nOut >= vfSpent.size())
557 return (!!vfSpent[nOut]);
560 int64 GetDebit() const
566 nDebitCached = pwallet->GetDebit(*this);
571 int64 GetCredit(bool fUseCache=true) const
573 // Must wait until coinbase is safely deep enough in the chain before valuing it
574 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
577 // GetBalance can assume transactions in mapWallet won't change
578 if (fUseCache && fCreditCached)
579 return nCreditCached;
580 nCreditCached = pwallet->GetCredit(*this);
581 fCreditCached = true;
582 return nCreditCached;
585 int64 GetAvailableCredit(bool fUseCache=true) const
587 // Must wait until coinbase is safely deep enough in the chain before valuing it
588 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
591 if (fUseCache && fAvailableCreditCached)
592 return nAvailableCreditCached;
595 for (unsigned int i = 0; i < vout.size(); i++)
599 const CTxOut &txout = vout[i];
600 nCredit += pwallet->GetCredit(txout);
601 if (!MoneyRange(nCredit))
602 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
606 nAvailableCreditCached = nCredit;
607 fAvailableCreditCached = true;
612 int64 GetChange() const
615 return nChangeCached;
616 nChangeCached = pwallet->GetChange(*this);
617 fChangeCached = true;
618 return nChangeCached;
621 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
622 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
624 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
625 int64& nSent, int64& nFee) const;
627 bool IsFromMe() const
629 return (GetDebit() > 0);
632 bool IsConfirmed() const
634 // Quick answer in most cases
637 if (GetDepthInMainChain() >= 1)
639 if (!IsFromMe()) // using wtx's cached debit
642 // If no confirmations but it's from us, we can still
643 // consider it confirmed if all dependencies are confirmed
644 std::map<uint256, const CMerkleTx*> mapPrev;
645 std::vector<const CMerkleTx*> vWorkQueue;
646 vWorkQueue.reserve(vtxPrev.size()+1);
647 vWorkQueue.push_back(this);
648 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
650 const CMerkleTx* ptx = vWorkQueue[i];
654 if (ptx->GetDepthInMainChain() >= 1)
656 if (!pwallet->IsFromMe(*ptx))
661 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
662 mapPrev[tx.GetHash()] = &tx;
665 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
667 if (!mapPrev.count(txin.prevout.hash))
669 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
677 int64 GetTxTime() const;
678 int GetRequestCount() const;
680 void AddSupportingTransactions(CTxDB& txdb);
682 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
683 bool AcceptWalletTransaction();
685 void RelayWalletTransaction(CTxDB& txdb);
686 void RelayWalletTransaction();
699 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
701 tx = txIn; i = iIn; nDepth = nDepthIn;
704 std::string ToString() const
706 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
711 printf("%s\n", ToString().c_str());
718 /** Private key that includes an expiration date in case it never gets used. */
725 std::string strComment;
726 //// todo: add something to note what created it (user, getnewaddress, change)
727 //// maybe should have a map<string, string> property map
729 CWalletKey(int64 nExpires=0)
731 nTimeCreated = (nExpires ? GetTime() : 0);
732 nTimeExpires = nExpires;
737 if (!(nType & SER_GETHASH))
739 READWRITE(vchPrivKey);
740 READWRITE(nTimeCreated);
741 READWRITE(nTimeExpires);
742 READWRITE(strComment);
751 /** Account information.
752 * Stored in wallet with key "acc"+string account name.
766 vchPubKey = CPubKey();
771 if (!(nType & SER_GETHASH))
773 READWRITE(vchPubKey);
779 /** Internal transfers.
780 * Database key is acentry<account><counter>.
782 class CAccountingEntry
785 std::string strAccount;
788 std::string strOtherAccount;
789 std::string strComment;
791 int64 nOrderPos; // position in ordered transaction list
804 strOtherAccount.clear();
811 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
812 if (!(nType & SER_GETHASH))
814 // Note: strAccount is serialized as part of the key, not here.
815 READWRITE(nCreditDebit);
817 READWRITE(strOtherAccount);
821 WriteOrderPos(nOrderPos, me.mapValue);
823 if (!(mapValue.empty() && _ssExtra.empty()))
825 CDataStream ss(nType, nVersion);
826 ss.insert(ss.begin(), '\0');
828 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
829 me.strComment.append(ss.str());
833 READWRITE(strComment);
835 size_t nSepPos = strComment.find("\0", 0, 1);
839 if (std::string::npos != nSepPos)
841 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
843 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
845 ReadOrderPos(me.nOrderPos, me.mapValue);
847 if (std::string::npos != nSepPos)
848 me.strComment.erase(nSepPos);
850 me.mapValue.erase("n");
854 std::vector<char> _ssExtra;
857 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);