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"
22 extern unsigned int nStakeMaxAge;
23 extern bool fWalletUnlockMintOnly;
24 extern bool fConfChange;
25 class CAccountingEntry;
31 // Set of selected transactions
32 typedef std::set<std::pair<const CWalletTx*,unsigned int> > CoinsSet;
34 /** (client) version numbers for particular wallet features */
37 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
39 FEATURE_WALLETCRYPT = 40000, // wallet encryption
40 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
41 FEATURE_MALLKEY = 60017,
42 FEATURE_LATEST = 60017
45 /** A key pool entry */
57 CKeyPool(const CPubKey& vchPubKeyIn)
60 vchPubKey = vchPubKeyIn;
65 if (!(nType & SER_GETHASH))
72 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
73 * and provides the ability to create new transactions.
75 class CWallet : public CCryptoKeyStore
78 bool SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl *coinControl=NULL) const;
80 CWalletDB *pwalletdbEncryption, *pwalletdbDecryption;
82 // the current wallet version: clients below this version are not able to load the wallet
85 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
86 int nWalletMaxVersion;
91 // stake mining statistics
92 uint64_t nKernelsTried;
93 uint64_t nCoinDaysTried;
96 mutable CCriticalSection cs_wallet;
99 std::string strWalletFile;
101 std::set<int64_t> setKeyPool;
103 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
104 std::map<CMalleableKeyView, CKeyMetadata> mapMalleableKeyMetadata;
107 std::map<CBitcoinAddress, CKeyMetadata> mapKeyMetadata;
109 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
110 MasterKeyMap mapMasterKeys;
111 unsigned int nMasterKeyMaxID;
117 CWallet(std::string strWalletFileIn)
121 strWalletFile = strWalletFileIn;
126 nWalletVersion = FEATURE_BASE;
127 nWalletMaxVersion = FEATURE_BASE;
130 pwalletdbEncryption = NULL;
131 pwalletdbDecryption = NULL;
140 std::map<uint256, CWalletTx> mapWallet;
141 std::vector<uint256> vMintingWalletUpdated;
142 int64_t nOrderPosNext;
143 std::map<uint256, int> mapRequestCount;
145 std::map<CBitcoinAddress, std::string> mapAddressBook;
147 CPubKey vchDefaultKey;
148 int64_t nTimeFirstKey;
150 const CWalletTx* GetWalletTx(const uint256& hash) const;
152 // check whether we are allowed to upgrade (or already support) to the named feature
153 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
155 void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const;
156 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
157 bool SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
159 // Simple select (without randomization)
160 bool SelectCoinsSimple(int64_t nTargetValue, int64_t nMinValue, int64_t nMaxValue, unsigned int nSpendTime, int nMinConf, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
162 // keystore implementation
163 // Generate a new key
164 CPubKey GenerateNewKey();
165 CMalleableKeyView GenerateNewMalleableKey();
166 // Adds a key to the store, and saves it to disk.
167 bool AddKey(const CKey& key);
168 bool AddKey(const CMalleableKey& mKey);
169 // Adds a key to the store, without saving it to disk (used by LoadWallet)
170 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
171 // Load metadata (used by LoadWallet)
172 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
173 bool LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata);
175 // Load malleable key without saving it to disk (used by LoadWallet)
176 bool LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH) { return CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH); }
177 bool LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH) { return CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH); }
179 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
181 // Adds an encrypted key to the store, and saves it to disk.
182 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
183 bool AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH);
184 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
185 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
186 bool AddCScript(const CScript& redeemScript);
187 bool LoadCScript(const CScript& redeemScript);
189 // Adds a watch-only address to the store, and saves it to disk.
190 bool AddWatchOnly(const CScript &dest);
191 bool RemoveWatchOnly(const CScript &dest);
192 // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
193 bool LoadWatchOnly(const CScript &dest);
195 bool Unlock(const SecureString& strWalletPassphrase);
196 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
197 bool EncryptWallet(const SecureString& strWalletPassphrase);
198 bool DecryptWallet(const SecureString& strWalletPassphrase);
200 void GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const;
203 /** Increment the next transaction order id
204 @return next transaction order id
206 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
208 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
209 typedef std::multimap<int64_t, TxPair > TxItems;
211 /** Get the wallet's activity log
212 @return multimap of ordered transactions and accounting entries
213 @warning Returned pointers are *only* valid within the scope of passed acentries
215 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
218 bool AddToWallet(const CWalletTx& wtxIn);
219 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
220 bool EraseFromWallet(uint256 hash);
222 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
223 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
224 int ScanForWalletTransaction(const uint256& hashTx);
225 void ReacceptWalletTransactions();
226 void ResendWalletTransactions(int64_t nBestBlockTime);
227 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
228 int64_t GetBalance() const;
229 int64_t GetWatchOnlyBalance() const;
230 int64_t GetUnconfirmedBalance() const;
231 int64_t GetUnconfirmedWatchOnlyBalance() const;
232 int64_t GetImmatureBalance() const;
233 int64_t GetImmatureWatchOnlyBalance() const;
234 int64_t GetStake() const;
235 int64_t GetNewMint() const;
236 int64_t GetWatchOnlyStake() const;
237 int64_t GetWatchOnlyNewMint() const;
238 bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
239 bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
240 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
242 void GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight);
243 bool CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nTime, uint32_t nBits, CTransaction &txNew, CKey& key);
244 bool MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nMaxValue, std::list<uint256>& listMerged);
246 std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
248 bool NewKeyPool(unsigned int nSize = 0);
249 bool TopUpKeyPool(unsigned int nSize = 0);
250 int64_t AddReserveKey(const CKeyPool& keypool);
251 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
252 void KeepKey(int64_t nIndex);
253 void ReturnKey(int64_t nIndex);
254 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
255 int64_t GetOldestKeyPoolTime();
256 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
258 std::set< std::set<CBitcoinAddress> > GetAddressGroupings();
259 std::map<CBitcoinAddress, int64_t> GetAddressBalances();
261 isminetype IsMine(const CTxIn& txin) const;
262 int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
263 isminetype IsMine(const CTxOut& txout) const;
264 int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const;
265 bool IsChange(const CTxOut& txout) const;
266 int64_t GetChange(const CTxOut& txout) const;
267 bool IsMine(const CTransaction& tx) const;
268 bool IsFromMe(const CTransaction& tx) const;
269 int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const;
270 int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const;
271 int64_t GetChange(const CTransaction& tx) const;
272 void SetBestChain(const CBlockLocator& loc);
274 DBErrors LoadWallet(bool& fFirstRunRet);
275 DBErrors ZapWalletTx();
277 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
278 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
279 bool DelAddressBookName(const CBitcoinAddress& address);
280 void UpdatedTransaction(const uint256 &hashTx);
281 void PrintWallet(const CBlock& block);
283 void Inventory(const uint256 &hash)
287 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
288 if (mi != mapRequestCount.end())
293 unsigned int GetKeyPoolSize()
295 return (unsigned int)(setKeyPool.size());
298 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
299 bool SetDefaultKey(const CPubKey &vchPubKey);
301 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
302 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
304 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
305 bool SetMaxVersion(int nVersion);
307 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
308 int GetVersion() { return nWalletVersion; }
310 void FixSpentCoins(int& nMismatchSpent, int64_t& nBalanceInQuestion, bool fCheckOnly = false);
311 void DisableTransaction(const CTransaction &tx);
313 /** Address book entry changed.
314 * @note called with lock cs_wallet held.
316 boost::signals2::signal<void (CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
318 /** Wallet transaction added, removed or updated.
319 * @note called with lock cs_wallet held.
321 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
323 /** Watch-only address added */
324 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
327 /** A key allocated from the key pool. */
335 CReserveKey(CWallet* pwalletIn)
348 CPubKey GetReservedKey();
353 typedef std::map<std::string, std::string> mapValue_t;
356 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
358 if (!mapValue.count("n"))
360 nOrderPos = -1; // TODO: calculate elsewhere
363 nOrderPos = atoi64(mapValue["n"].c_str());
367 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
371 mapValue["n"] = i64tostr(nOrderPos);
375 /** A transaction with a bunch of additional info that only the owner cares about.
376 * It includes any unrecorded transactions needed to link it back to the block chain.
378 class CWalletTx : public CMerkleTx
381 const CWallet* pwallet;
384 std::vector<CMerkleTx> vtxPrev;
386 std::vector<std::pair<std::string, std::string> > vOrderForm;
387 unsigned int fTimeReceivedIsTxTime;
388 unsigned int nTimeReceived; // time received by this node
389 unsigned int nTimeSmart;
391 std::string strFromAccount;
392 std::vector<char> vfSpent; // which outputs are already spent
393 int64_t nOrderPos; // position in ordered transaction list
396 mutable bool fDebitCached;
397 mutable bool fWatchDebitCached;
398 mutable bool fCreditCached;
399 mutable bool fWatchCreditCached;
400 mutable bool fAvailableCreditCached;
401 mutable bool fImmatureCreditCached;
402 mutable bool fImmatureWatchCreditCached;
403 mutable bool fAvailableWatchCreditCached;
404 mutable bool fChangeCached;
405 mutable int64_t nDebitCached;
406 mutable int64_t nWatchDebitCached;
407 mutable int64_t nCreditCached;
408 mutable int64_t nWatchCreditCached;
409 mutable int64_t nAvailableCreditCached;
410 mutable int64_t nImmatureCreditCached;
411 mutable int64_t nImmatureWatchCreditCached;
412 mutable int64_t nAvailableWatchCreditCached;
413 mutable int64_t nChangeCached;
420 CWalletTx(const CWallet* pwalletIn)
425 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
430 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
435 void Init(const CWallet* pwalletIn)
441 fTimeReceivedIsTxTime = false;
445 strFromAccount.clear();
447 fDebitCached = false;
448 fWatchDebitCached = false;
449 fCreditCached = false;
450 fWatchCreditCached = false;
451 fAvailableCreditCached = false;
452 fAvailableWatchCreditCached = false;
453 fImmatureCreditCached = false;
454 fImmatureWatchCreditCached = false;
455 fChangeCached = false;
457 nWatchDebitCached = 0;
459 nWatchCreditCached = 0;
460 nAvailableCreditCached = 0;
461 nAvailableWatchCreditCached = 0;
462 nImmatureCreditCached = 0;
463 nImmatureWatchCreditCached = 0;
470 CWalletTx* pthis = const_cast<CWalletTx*>(this);
477 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
480 BOOST_FOREACH(char f, vfSpent)
482 str += (f ? '1' : '0');
486 pthis->mapValue["spent"] = str;
488 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
491 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
494 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
497 READWRITE(vOrderForm);
498 READWRITE(fTimeReceivedIsTxTime);
499 READWRITE(nTimeReceived);
505 pthis->strFromAccount = pthis->mapValue["fromaccount"];
507 if (mapValue.count("spent"))
508 BOOST_FOREACH(char c, pthis->mapValue["spent"])
509 pthis->vfSpent.push_back(c != '0');
511 pthis->vfSpent.assign(vout.size(), fSpent);
513 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
515 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
518 pthis->mapValue.erase("fromaccount");
519 pthis->mapValue.erase("version");
520 pthis->mapValue.erase("spent");
521 pthis->mapValue.erase("n");
522 pthis->mapValue.erase("timesmart");
525 // marks certain txout's as spent
526 // returns true if any update took place
527 bool UpdateSpent(const std::vector<char>& vfNewSpent);
529 // make sure balances are recalculated
531 void BindWallet(CWallet *pwalletIn);
532 void MarkSpent(unsigned int nOut);
533 void MarkUnspent(unsigned int nOut);
534 bool IsSpent(unsigned int nOut) const;
536 int64_t GetDebit(const isminefilter& filter) const;
537 int64_t GetCredit(const isminefilter& filter) const;
538 int64_t GetImmatureCredit(bool fUseCache=true) const;
539 int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const;
540 int64_t GetAvailableCredit(bool fUseCache=true) const;
541 int64_t GetAvailableWatchCredit(bool fUseCache=true) const;
542 int64_t GetChange() const;
544 void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
545 std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
547 void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
548 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
550 bool IsFromMe(const isminefilter& filter) const
552 return (GetDebit(filter) > 0);
555 bool InMempool() const;
556 bool IsTrusted() const;
560 int64_t GetTxTime() const;
561 int GetRequestCount() const;
563 void AddSupportingTransactions(CTxDB& txdb);
565 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
566 bool AcceptWalletTransaction();
568 bool RelayWalletTransaction(CTxDB& txdb);
569 bool RelayWalletTransaction();
583 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
585 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
588 std::string ToString() const
590 return strprintf("COutput(%s, %d, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, fSpendable, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
597 /** Private key that includes an expiration date in case it never gets used. */
602 int64_t nTimeCreated;
603 int64_t nTimeExpires;
604 std::string strComment;
605 //// todo: add something to note what created it (user, getnewaddress, change)
606 //// maybe should have a map<string, string> property map
608 CWalletKey(int64_t nExpires=0)
610 nTimeCreated = (nExpires ? GetTime() : 0);
611 nTimeExpires = nExpires;
616 if (!(nType & SER_GETHASH))
618 READWRITE(vchPrivKey);
619 READWRITE(nTimeCreated);
620 READWRITE(nTimeExpires);
621 READWRITE(strComment);
630 /** Account information.
631 * Stored in wallet with key "acc"+string account name.
645 vchPubKey = CPubKey();
650 if (!(nType & SER_GETHASH))
652 READWRITE(vchPubKey);
658 /** Internal transfers.
659 * Database key is acentry<account><counter>.
661 class CAccountingEntry
664 std::string strAccount;
665 int64_t nCreditDebit;
667 std::string strOtherAccount;
668 std::string strComment;
670 int64_t nOrderPos; // position in ordered transaction list
683 strOtherAccount.clear();
690 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
691 if (!(nType & SER_GETHASH))
693 // Note: strAccount is serialized as part of the key, not here.
694 READWRITE(nCreditDebit);
696 READWRITE(strOtherAccount);
700 WriteOrderPos(nOrderPos, me.mapValue);
702 if (!(mapValue.empty() && _ssExtra.empty()))
704 CDataStream ss(nType, nVersion);
705 ss.insert(ss.begin(), '\0');
707 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
708 me.strComment.append(ss.str());
712 READWRITE(strComment);
714 size_t nSepPos = strComment.find("\0", 0, 1);
718 if (std::string::npos != nSepPos)
720 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
722 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
724 ReadOrderPos(me.nOrderPos, me.mapValue);
726 if (std::string::npos != nSepPos)
727 me.strComment.erase(nSepPos);
729 me.mapValue.erase("n");
733 std::vector<char> _ssExtra;
736 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);