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);
181 uint64 GetStakeMintPower(const CKeyStore& keystore);
182 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew);
184 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
185 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
189 int64 AddReserveKey(const CKeyPool& keypool);
190 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
191 void KeepKey(int64 nIndex);
192 void ReturnKey(int64 nIndex);
193 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
194 int64 GetOldestKeyPoolTime();
195 void GetAllReserveKeys(std::set<CKeyID>& setAddress);
197 std::set< std::set<CTxDestination> > GetAddressGroupings();
198 std::map<CTxDestination, int64> GetAddressBalances();
200 bool IsMine(const CTxIn& txin) const;
201 int64 GetDebit(const CTxIn& txin) const;
202 bool IsMine(const CTxOut& txout) const
204 return ::IsMine(*this, txout.scriptPubKey);
206 int64 GetCredit(const CTxOut& txout) const
208 if (!MoneyRange(txout.nValue))
209 throw std::runtime_error("CWallet::GetCredit() : value out of range");
210 return (IsMine(txout) ? txout.nValue : 0);
212 bool IsChange(const CTxOut& txout) const;
213 int64 GetChange(const CTxOut& txout) const
215 if (!MoneyRange(txout.nValue))
216 throw std::runtime_error("CWallet::GetChange() : value out of range");
217 return (IsChange(txout) ? txout.nValue : 0);
219 bool IsMine(const CTransaction& tx) const
221 BOOST_FOREACH(const CTxOut& txout, tx.vout)
226 bool IsFromMe(const CTransaction& tx) const
228 return (GetDebit(tx) > 0);
230 int64 GetDebit(const CTransaction& tx) const
233 BOOST_FOREACH(const CTxIn& txin, tx.vin)
235 nDebit += GetDebit(txin);
236 if (!MoneyRange(nDebit))
237 throw std::runtime_error("CWallet::GetDebit() : value out of range");
241 int64 GetCredit(const CTransaction& tx) const
244 BOOST_FOREACH(const CTxOut& txout, tx.vout)
246 nCredit += GetCredit(txout);
247 if (!MoneyRange(nCredit))
248 throw std::runtime_error("CWallet::GetCredit() : value out of range");
252 int64 GetChange(const CTransaction& tx) const
255 BOOST_FOREACH(const CTxOut& txout, tx.vout)
257 nChange += GetChange(txout);
258 if (!MoneyRange(nChange))
259 throw std::runtime_error("CWallet::GetChange() : value out of range");
263 void SetBestChain(const CBlockLocator& loc);
265 DBErrors LoadWallet(bool& fFirstRunRet);
267 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
269 bool DelAddressBookName(const CTxDestination& address);
271 void UpdatedTransaction(const uint256 &hashTx);
273 void PrintWallet(const CBlock& block);
275 void Inventory(const uint256 &hash)
279 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
280 if (mi != mapRequestCount.end())
287 return setKeyPool.size();
290 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
292 bool SetDefaultKey(const CPubKey &vchPubKey);
294 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
295 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
297 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
298 bool SetMaxVersion(int nVersion);
300 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
301 int GetVersion() { return nWalletVersion; }
303 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
304 void DisableTransaction(const CTransaction &tx);
306 /** Address book entry changed.
307 * @note called with lock cs_wallet held.
309 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
311 /** Wallet transaction added, removed or updated.
312 * @note called with lock cs_wallet held.
314 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
317 /** A key allocated from the key pool. */
325 CReserveKey(CWallet* pwalletIn)
338 CPubKey GetReservedKey();
343 typedef std::map<std::string, std::string> mapValue_t;
346 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
348 if (!mapValue.count("n"))
350 nOrderPos = -1; // TODO: calculate elsewhere
353 nOrderPos = atoi64(mapValue["n"].c_str());
357 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
361 mapValue["n"] = i64tostr(nOrderPos);
365 /** A transaction with a bunch of additional info that only the owner cares about.
366 * It includes any unrecorded transactions needed to link it back to the block chain.
368 class CWalletTx : public CMerkleTx
371 const CWallet* pwallet;
374 std::vector<CMerkleTx> vtxPrev;
376 std::vector<std::pair<std::string, std::string> > vOrderForm;
377 unsigned int fTimeReceivedIsTxTime;
378 unsigned int nTimeReceived; // time received by this node
379 unsigned int nTimeSmart;
381 std::string strFromAccount;
382 std::vector<char> vfSpent; // which outputs are already spent
383 int64 nOrderPos; // position in ordered transaction list
386 mutable bool fDebitCached;
387 mutable bool fCreditCached;
388 mutable bool fAvailableCreditCached;
389 mutable bool fChangeCached;
390 mutable int64 nDebitCached;
391 mutable int64 nCreditCached;
392 mutable int64 nAvailableCreditCached;
393 mutable int64 nChangeCached;
400 CWalletTx(const CWallet* pwalletIn)
405 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
410 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
415 void Init(const CWallet* pwalletIn)
421 fTimeReceivedIsTxTime = false;
425 strFromAccount.clear();
427 fDebitCached = false;
428 fCreditCached = false;
429 fAvailableCreditCached = false;
430 fChangeCached = false;
433 nAvailableCreditCached = 0;
440 CWalletTx* pthis = const_cast<CWalletTx*>(this);
447 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
450 BOOST_FOREACH(char f, vfSpent)
452 str += (f ? '1' : '0');
456 pthis->mapValue["spent"] = str;
458 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
461 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
464 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
467 READWRITE(vOrderForm);
468 READWRITE(fTimeReceivedIsTxTime);
469 READWRITE(nTimeReceived);
475 pthis->strFromAccount = pthis->mapValue["fromaccount"];
477 if (mapValue.count("spent"))
478 BOOST_FOREACH(char c, pthis->mapValue["spent"])
479 pthis->vfSpent.push_back(c != '0');
481 pthis->vfSpent.assign(vout.size(), fSpent);
483 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
485 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
488 pthis->mapValue.erase("fromaccount");
489 pthis->mapValue.erase("version");
490 pthis->mapValue.erase("spent");
491 pthis->mapValue.erase("n");
492 pthis->mapValue.erase("timesmart");
495 // marks certain txout's as spent
496 // returns true if any update took place
497 bool UpdateSpent(const std::vector<char>& vfNewSpent)
499 bool fReturn = false;
500 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
502 if (i == vfSpent.size())
505 if (vfNewSpent[i] && !vfSpent[i])
509 fAvailableCreditCached = false;
515 // make sure balances are recalculated
518 fCreditCached = false;
519 fAvailableCreditCached = false;
520 fDebitCached = false;
521 fChangeCached = false;
524 void BindWallet(CWallet *pwalletIn)
530 void MarkSpent(unsigned int nOut)
532 if (nOut >= vout.size())
533 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
534 vfSpent.resize(vout.size());
537 vfSpent[nOut] = true;
538 fAvailableCreditCached = false;
542 void MarkUnspent(unsigned int nOut)
544 if (nOut >= vout.size())
545 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
546 vfSpent.resize(vout.size());
549 vfSpent[nOut] = false;
550 fAvailableCreditCached = false;
554 bool IsSpent(unsigned int nOut) const
556 if (nOut >= vout.size())
557 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
558 if (nOut >= vfSpent.size())
560 return (!!vfSpent[nOut]);
563 int64 GetDebit() const
569 nDebitCached = pwallet->GetDebit(*this);
574 int64 GetCredit(bool fUseCache=true) const
576 // Must wait until coinbase is safely deep enough in the chain before valuing it
577 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
580 // GetBalance can assume transactions in mapWallet won't change
581 if (fUseCache && fCreditCached)
582 return nCreditCached;
583 nCreditCached = pwallet->GetCredit(*this);
584 fCreditCached = true;
585 return nCreditCached;
588 int64 GetAvailableCredit(bool fUseCache=true) const
590 // Must wait until coinbase is safely deep enough in the chain before valuing it
591 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
594 if (fUseCache && fAvailableCreditCached)
595 return nAvailableCreditCached;
598 for (unsigned int i = 0; i < vout.size(); i++)
602 const CTxOut &txout = vout[i];
603 nCredit += pwallet->GetCredit(txout);
604 if (!MoneyRange(nCredit))
605 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
609 nAvailableCreditCached = nCredit;
610 fAvailableCreditCached = true;
615 int64 GetChange() const
618 return nChangeCached;
619 nChangeCached = pwallet->GetChange(*this);
620 fChangeCached = true;
621 return nChangeCached;
624 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
625 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
627 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
628 int64& nSent, int64& nFee) const;
630 bool IsFromMe() const
632 return (GetDebit() > 0);
635 bool IsConfirmed() const
637 // Quick answer in most cases
640 if (GetDepthInMainChain() >= 1)
642 if (!IsFromMe()) // using wtx's cached debit
645 // If no confirmations but it's from us, we can still
646 // consider it confirmed if all dependencies are confirmed
647 std::map<uint256, const CMerkleTx*> mapPrev;
648 std::vector<const CMerkleTx*> vWorkQueue;
649 vWorkQueue.reserve(vtxPrev.size()+1);
650 vWorkQueue.push_back(this);
651 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
653 const CMerkleTx* ptx = vWorkQueue[i];
657 if (ptx->GetDepthInMainChain() >= 1)
659 if (!pwallet->IsFromMe(*ptx))
664 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
665 mapPrev[tx.GetHash()] = &tx;
668 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
670 if (!mapPrev.count(txin.prevout.hash))
672 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
680 int64 GetTxTime() const;
681 int GetRequestCount() const;
683 void AddSupportingTransactions(CTxDB& txdb);
685 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
686 bool AcceptWalletTransaction();
688 void RelayWalletTransaction(CTxDB& txdb);
689 void RelayWalletTransaction();
702 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
704 tx = txIn; i = iIn; nDepth = nDepthIn;
707 std::string ToString() const
709 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
714 printf("%s\n", ToString().c_str());
721 /** Private key that includes an expiration date in case it never gets used. */
728 std::string strComment;
729 //// todo: add something to note what created it (user, getnewaddress, change)
730 //// maybe should have a map<string, string> property map
732 CWalletKey(int64 nExpires=0)
734 nTimeCreated = (nExpires ? GetTime() : 0);
735 nTimeExpires = nExpires;
740 if (!(nType & SER_GETHASH))
742 READWRITE(vchPrivKey);
743 READWRITE(nTimeCreated);
744 READWRITE(nTimeExpires);
745 READWRITE(strComment);
754 /** Account information.
755 * Stored in wallet with key "acc"+string account name.
769 vchPubKey = CPubKey();
774 if (!(nType & SER_GETHASH))
776 READWRITE(vchPubKey);
782 /** Internal transfers.
783 * Database key is acentry<account><counter>.
785 class CAccountingEntry
788 std::string strAccount;
791 std::string strOtherAccount;
792 std::string strComment;
794 int64 nOrderPos; // position in ordered transaction list
807 strOtherAccount.clear();
814 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
815 if (!(nType & SER_GETHASH))
817 // Note: strAccount is serialized as part of the key, not here.
818 READWRITE(nCreditDebit);
820 READWRITE(strOtherAccount);
824 WriteOrderPos(nOrderPos, me.mapValue);
826 if (!(mapValue.empty() && _ssExtra.empty()))
828 CDataStream ss(nType, nVersion);
829 ss.insert(ss.begin(), '\0');
831 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
832 me.strComment.append(ss.str());
836 READWRITE(strComment);
838 size_t nSepPos = strComment.find("\0", 0, 1);
842 if (std::string::npos != nSepPos)
844 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
846 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
848 ReadOrderPos(me.nOrderPos, me.mapValue);
850 if (std::string::npos != nSepPos)
851 me.strComment.erase(nSepPos);
853 me.mapValue.erase("n");
857 std::vector<char> _ssExtra;
860 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);