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;
88 // stake mining statistics
89 uint64_t nKernelsTried;
90 uint64_t nCoinDaysTried;
93 mutable CCriticalSection cs_wallet;
96 std::string strWalletFile;
98 std::set<int64_t> setKeyPool;
100 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
101 std::map<CMalleableKeyView, CKeyMetadata> mapMalleableKeyMetadata;
104 std::map<CBitcoinAddress, CKeyMetadata> mapKeyMetadata;
106 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
107 MasterKeyMap mapMasterKeys;
108 unsigned int nMasterKeyMaxID;
114 CWallet(std::string strWalletFileIn)
118 strWalletFile = strWalletFileIn;
123 nWalletVersion = FEATURE_BASE;
124 nWalletMaxVersion = FEATURE_BASE;
127 pwalletdbEncryption = NULL;
128 pwalletdbDecryption = NULL;
135 std::map<uint256, CWalletTx> mapWallet;
136 std::vector<uint256> vMintingWalletUpdated;
137 int64_t nOrderPosNext;
138 std::map<uint256, int> mapRequestCount;
140 std::map<CBitcoinAddress, std::string> mapAddressBook;
142 CPubKey vchDefaultKey;
143 int64_t nTimeFirstKey;
145 const CWalletTx* GetWalletTx(const uint256& hash) const;
147 // check whether we are allowed to upgrade (or already support) to the named feature
148 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
150 void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const;
151 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
152 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;
154 // Simple select (without randomization)
155 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;
157 // keystore implementation
158 // Generate a new key
159 CPubKey GenerateNewKey();
160 CMalleableKeyView GenerateNewMalleableKey();
161 // Adds a key to the store, and saves it to disk.
162 bool AddKey(const CKey& key);
163 bool AddKey(const CMalleableKey& mKey);
164 // Adds a key to the store, without saving it to disk (used by LoadWallet)
165 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
166 // Load metadata (used by LoadWallet)
167 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
168 bool LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata);
170 // Load malleable key without saving it to disk (used by LoadWallet)
171 bool LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH) { return CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH); }
172 bool LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH) { return CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH); }
174 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
176 // Adds an encrypted key to the store, and saves it to disk.
177 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
178 bool AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH);
179 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
180 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
181 bool AddCScript(const CScript& redeemScript);
182 bool LoadCScript(const CScript& redeemScript);
184 // Adds a watch-only address to the store, and saves it to disk.
185 bool AddWatchOnly(const CScript &dest);
186 bool RemoveWatchOnly(const CScript &dest);
187 // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
188 bool LoadWatchOnly(const CScript &dest);
190 bool Unlock(const SecureString& strWalletPassphrase);
191 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
192 bool EncryptWallet(const SecureString& strWalletPassphrase);
193 bool DecryptWallet(const SecureString& strWalletPassphrase);
195 void GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const;
196 bool GetPEM(const CKeyID &keyID, const std::string &fileName, const SecureString &strPassPhrase) const;
199 /** Increment the next transaction order id
200 @return next transaction order id
202 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
204 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
205 typedef std::multimap<int64_t, TxPair > TxItems;
207 /** Get the wallet's activity log
208 @return multimap of ordered transactions and accounting entries
209 @warning Returned pointers are *only* valid within the scope of passed acentries
211 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
214 bool AddToWallet(const CWalletTx& wtxIn);
215 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
216 bool EraseFromWallet(uint256 hash);
218 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
219 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
220 int ScanForWalletTransaction(const uint256& hashTx);
221 void ReacceptWalletTransactions();
222 void ResendWalletTransactions(bool fForceResend=false);
223 int64_t GetBalance() const;
224 int64_t GetWatchOnlyBalance() const;
225 int64_t GetUnconfirmedBalance() const;
226 int64_t GetUnconfirmedWatchOnlyBalance() const;
227 int64_t GetImmatureBalance() const;
228 int64_t GetImmatureWatchOnlyBalance() const;
229 int64_t GetStake() const;
230 int64_t GetNewMint() const;
231 int64_t GetWatchOnlyStake() const;
232 int64_t GetWatchOnlyNewMint() const;
233 bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
234 bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
235 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
237 void GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight);
238 bool CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nTime, uint32_t nBits, CTransaction &txNew, CKey& key);
239 bool MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nMaxValue, std::list<uint256>& listMerged);
241 std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
243 bool NewKeyPool(unsigned int nSize = 0);
244 bool TopUpKeyPool(unsigned int nSize = 0);
245 int64_t AddReserveKey(const CKeyPool& keypool);
246 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
247 void KeepKey(int64_t nIndex);
248 void ReturnKey(int64_t nIndex);
249 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
250 int64_t GetOldestKeyPoolTime();
251 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
253 std::set< std::set<CBitcoinAddress> > GetAddressGroupings();
254 std::map<CBitcoinAddress, int64_t> GetAddressBalances();
256 isminetype IsMine(const CTxIn& txin) const;
257 int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
258 isminetype IsMine(const CTxOut& txout) const;
259 int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const;
260 bool IsChange(const CTxOut& txout) const;
261 int64_t GetChange(const CTxOut& txout) const;
262 bool IsMine(const CTransaction& tx) const;
263 bool IsFromMe(const CTransaction& tx) const;
264 int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const;
265 int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const;
266 int64_t GetChange(const CTransaction& tx) const;
267 void SetBestChain(const CBlockLocator& loc);
269 DBErrors LoadWallet(bool& fFirstRunRet);
270 DBErrors ZapWalletTx();
272 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
273 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
274 bool DelAddressBookName(const CBitcoinAddress& address);
275 void UpdatedTransaction(const uint256 &hashTx);
276 void PrintWallet(const CBlock& block);
278 void Inventory(const uint256 &hash)
282 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
283 if (mi != mapRequestCount.end())
288 unsigned int GetKeyPoolSize()
290 return (unsigned int)(setKeyPool.size());
293 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
294 bool SetDefaultKey(const CPubKey &vchPubKey);
296 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
297 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
299 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
300 bool SetMaxVersion(int nVersion);
302 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
303 int GetVersion() { return nWalletVersion; }
305 void FixSpentCoins(int& nMismatchSpent, int64_t& nBalanceInQuestion, bool fCheckOnly = false);
306 void DisableTransaction(const CTransaction &tx);
308 /** Address book entry changed.
309 * @note called with lock cs_wallet held.
311 boost::signals2::signal<void (CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
313 /** Wallet transaction added, removed or updated.
314 * @note called with lock cs_wallet held.
316 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
318 /** Watch-only address added */
319 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
322 /** A key allocated from the key pool. */
330 CReserveKey(CWallet* pwalletIn)
343 CPubKey GetReservedKey();
348 typedef std::map<std::string, std::string> mapValue_t;
351 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
353 if (!mapValue.count("n"))
355 nOrderPos = -1; // TODO: calculate elsewhere
358 nOrderPos = atoi64(mapValue["n"].c_str());
362 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
366 mapValue["n"] = i64tostr(nOrderPos);
370 /** A transaction with a bunch of additional info that only the owner cares about.
371 * It includes any unrecorded transactions needed to link it back to the block chain.
373 class CWalletTx : public CMerkleTx
376 const CWallet* pwallet;
379 std::vector<CMerkleTx> vtxPrev;
381 std::vector<std::pair<std::string, std::string> > vOrderForm;
382 unsigned int fTimeReceivedIsTxTime;
383 unsigned int nTimeReceived; // time received by this node
384 unsigned int nTimeSmart;
386 std::string strFromAccount;
387 std::vector<char> vfSpent; // which outputs are already spent
388 int64_t nOrderPos; // position in ordered transaction list
391 mutable bool fDebitCached;
392 mutable bool fWatchDebitCached;
393 mutable bool fCreditCached;
394 mutable bool fWatchCreditCached;
395 mutable bool fAvailableCreditCached;
396 mutable bool fImmatureCreditCached;
397 mutable bool fImmatureWatchCreditCached;
398 mutable bool fAvailableWatchCreditCached;
399 mutable bool fChangeCached;
400 mutable int64_t nDebitCached;
401 mutable int64_t nWatchDebitCached;
402 mutable int64_t nCreditCached;
403 mutable int64_t nWatchCreditCached;
404 mutable int64_t nAvailableCreditCached;
405 mutable int64_t nImmatureCreditCached;
406 mutable int64_t nImmatureWatchCreditCached;
407 mutable int64_t nAvailableWatchCreditCached;
408 mutable int64_t nChangeCached;
415 CWalletTx(const CWallet* pwalletIn)
420 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
425 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
430 void Init(const CWallet* pwalletIn)
436 fTimeReceivedIsTxTime = false;
440 strFromAccount.clear();
442 fDebitCached = false;
443 fWatchDebitCached = false;
444 fCreditCached = false;
445 fWatchCreditCached = false;
446 fAvailableCreditCached = false;
447 fAvailableWatchCreditCached = false;
448 fImmatureCreditCached = false;
449 fImmatureWatchCreditCached = false;
450 fChangeCached = false;
452 nWatchDebitCached = 0;
454 nWatchCreditCached = 0;
455 nAvailableCreditCached = 0;
456 nAvailableWatchCreditCached = 0;
457 nImmatureCreditCached = 0;
458 nImmatureWatchCreditCached = 0;
465 CWalletTx* pthis = const_cast<CWalletTx*>(this);
472 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
475 BOOST_FOREACH(char f, vfSpent)
477 str += (f ? '1' : '0');
481 pthis->mapValue["spent"] = str;
483 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
486 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
489 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
492 READWRITE(vOrderForm);
493 READWRITE(fTimeReceivedIsTxTime);
494 READWRITE(nTimeReceived);
500 pthis->strFromAccount = pthis->mapValue["fromaccount"];
502 if (mapValue.count("spent"))
503 BOOST_FOREACH(char c, pthis->mapValue["spent"])
504 pthis->vfSpent.push_back(c != '0');
506 pthis->vfSpent.assign(vout.size(), fSpent);
508 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
510 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
513 pthis->mapValue.erase("fromaccount");
514 pthis->mapValue.erase("version");
515 pthis->mapValue.erase("spent");
516 pthis->mapValue.erase("n");
517 pthis->mapValue.erase("timesmart");
520 // marks certain txout's as spent
521 // returns true if any update took place
522 bool UpdateSpent(const std::vector<char>& vfNewSpent)
524 bool fReturn = false;
525 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
527 if (i == vfSpent.size())
530 if (vfNewSpent[i] && !vfSpent[i])
534 fAvailableCreditCached = fAvailableWatchCreditCached = false;
540 // make sure balances are recalculated
543 fCreditCached = false;
544 fAvailableCreditCached = fAvailableWatchCreditCached = false;
545 fDebitCached = fWatchDebitCached = false;
546 fChangeCached = false;
549 void BindWallet(CWallet *pwalletIn)
555 void MarkSpent(unsigned int nOut)
557 if (nOut >= vout.size())
558 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
559 vfSpent.resize(vout.size());
562 vfSpent[nOut] = true;
563 fAvailableCreditCached = fAvailableWatchCreditCached = false;
567 void MarkUnspent(unsigned int nOut)
569 if (nOut >= vout.size())
570 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
571 vfSpent.resize(vout.size());
574 vfSpent[nOut] = false;
575 fAvailableCreditCached = fAvailableWatchCreditCached = false;
579 bool IsSpent(unsigned int nOut) const
581 if (nOut >= vout.size())
582 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
583 if (nOut >= vfSpent.size())
585 return (!!vfSpent[nOut]);
588 int64_t GetDebit(const isminefilter& filter) const;
589 int64_t GetCredit(const isminefilter& filter) const;
590 int64_t GetImmatureCredit(bool fUseCache=true) const;
591 int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const;
592 int64_t GetAvailableCredit(bool fUseCache=true) const;
593 int64_t GetAvailableWatchCredit(bool fUseCache=true) const;
594 int64_t GetChange() const;
596 void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
597 std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
599 void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
600 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
602 bool IsFromMe(const isminefilter& filter) const
604 return (GetDebit(filter) > 0);
607 bool InMempool() const;
608 bool IsTrusted() const;
612 int64_t GetTxTime() const;
613 int GetRequestCount() const;
615 void AddSupportingTransactions(CTxDB& txdb);
617 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
618 bool AcceptWalletTransaction();
620 void RelayWalletTransaction(CTxDB& txdb);
621 void RelayWalletTransaction();
635 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
637 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
640 std::string ToString() const
642 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());
649 /** Private key that includes an expiration date in case it never gets used. */
654 int64_t nTimeCreated;
655 int64_t nTimeExpires;
656 std::string strComment;
657 //// todo: add something to note what created it (user, getnewaddress, change)
658 //// maybe should have a map<string, string> property map
660 CWalletKey(int64_t nExpires=0)
662 nTimeCreated = (nExpires ? GetTime() : 0);
663 nTimeExpires = nExpires;
668 if (!(nType & SER_GETHASH))
670 READWRITE(vchPrivKey);
671 READWRITE(nTimeCreated);
672 READWRITE(nTimeExpires);
673 READWRITE(strComment);
682 /** Account information.
683 * Stored in wallet with key "acc"+string account name.
697 vchPubKey = CPubKey();
702 if (!(nType & SER_GETHASH))
704 READWRITE(vchPubKey);
710 /** Internal transfers.
711 * Database key is acentry<account><counter>.
713 class CAccountingEntry
716 std::string strAccount;
717 int64_t nCreditDebit;
719 std::string strOtherAccount;
720 std::string strComment;
722 int64_t nOrderPos; // position in ordered transaction list
735 strOtherAccount.clear();
742 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
743 if (!(nType & SER_GETHASH))
745 // Note: strAccount is serialized as part of the key, not here.
746 READWRITE(nCreditDebit);
748 READWRITE(strOtherAccount);
752 WriteOrderPos(nOrderPos, me.mapValue);
754 if (!(mapValue.empty() && _ssExtra.empty()))
756 CDataStream ss(nType, nVersion);
757 ss.insert(ss.begin(), '\0');
759 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
760 me.strComment.append(ss.str());
764 READWRITE(strComment);
766 size_t nSepPos = strComment.find("\0", 0, 1);
770 if (std::string::npos != nSepPos)
772 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
774 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
776 ReadOrderPos(me.nOrderPos, me.mapValue);
778 if (std::string::npos != nSepPos)
779 me.strComment.erase(nSepPos);
781 me.mapValue.erase("n");
785 std::vector<char> _ssExtra;
788 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);