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
52 CKeyPool() : nTime(GetTime()) {}
53 CKeyPool(const CPubKey& vchPubKeyIn) : nTime(GetTime()), vchPubKey(vchPubKeyIn) {}
57 if (!(nType & SER_GETHASH))
64 // A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
65 // and provides the ability to create new transactions.
67 class CWallet : public CCryptoKeyStore
70 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;
72 CWalletDB *pwalletdbEncryption, *pwalletdbDecryption;
74 // the current wallet version: clients below this version are not able to load the wallet
77 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
78 int nWalletMaxVersion;
83 // stake mining statistics
84 uint64_t nKernelsTried;
85 uint64_t nCoinDaysTried;
88 mutable CCriticalSection cs_wallet;
91 std::string strWalletFile;
93 std::set<int64_t> setKeyPool;
95 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
96 std::map<CMalleableKeyView, CKeyMetadata> mapMalleableKeyMetadata;
99 std::map<CBitcoinAddress, CKeyMetadata> mapKeyMetadata;
101 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
102 MasterKeyMap mapMasterKeys;
103 unsigned int nMasterKeyMaxID;
106 CWallet(std::string strWalletFileIn);
109 std::map<uint256, CWalletTx> mapWallet;
110 std::vector<uint256> vMintingWalletUpdated;
111 int64_t nOrderPosNext;
112 std::map<uint256, int> mapRequestCount;
114 std::map<CBitcoinAddress, std::string> mapAddressBook;
116 CPubKey vchDefaultKey;
117 int64_t nTimeFirstKey;
119 const CWalletTx* GetWalletTx(const uint256& hash) const;
121 // check whether we are allowed to upgrade (or already support) to the named feature
122 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
124 void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const;
125 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
126 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;
128 // Simple select (without randomization)
129 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;
131 // keystore implementation
132 // Generate a new key
133 CPubKey GenerateNewKey();
134 CMalleableKeyView GenerateNewMalleableKey();
135 // Adds a key to the store, and saves it to disk.
136 bool AddKey(const CKey& key);
137 bool AddKey(const CMalleableKey& mKey);
138 // Adds a key to the store, without saving it to disk (used by LoadWallet)
139 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
140 // Load metadata (used by LoadWallet)
141 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
142 bool LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata);
144 // Load malleable key without saving it to disk (used by LoadWallet)
145 bool LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH) { return CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH); }
146 bool LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH) { return CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH); }
148 bool LoadMinVersion(int nVersion);
150 // Adds an encrypted key to the store, and saves it to disk.
151 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
152 bool AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH);
153 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
154 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
155 bool AddCScript(const CScript& redeemScript);
156 bool LoadCScript(const CScript& redeemScript);
158 // Adds a watch-only address to the store, and saves it to disk.
159 bool AddWatchOnly(const CScript &dest);
160 bool RemoveWatchOnly(const CScript &dest);
161 // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
162 bool LoadWatchOnly(const CScript &dest);
164 bool Unlock(const SecureString& strWalletPassphrase);
165 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
166 bool EncryptWallet(const SecureString& strWalletPassphrase);
167 bool DecryptWallet(const SecureString& strWalletPassphrase);
169 void GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const;
170 bool GetPEM(const CKeyID &keyID, const std::string &fileName, const SecureString &strPassPhrase) const;
173 /** Increment the next transaction order id
174 @return next transaction order id
176 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
178 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
179 typedef std::multimap<int64_t, TxPair > TxItems;
181 /** Get the wallet's activity log
182 @return multimap of ordered transactions and accounting entries
183 @warning Returned pointers are *only* valid within the scope of passed acentries
185 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
188 bool AddToWallet(const CWalletTx& wtxIn);
189 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
190 bool EraseFromWallet(uint256 hash);
192 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
193 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
194 int ScanForWalletTransaction(const uint256& hashTx);
195 void ReacceptWalletTransactions();
196 void ResendWalletTransactions(int64_t nBestBlockTime);
197 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
198 int64_t GetBalance() const;
199 int64_t GetWatchOnlyBalance() const;
200 int64_t GetUnconfirmedBalance() const;
201 int64_t GetUnconfirmedWatchOnlyBalance() const;
202 int64_t GetImmatureBalance() const;
203 int64_t GetImmatureWatchOnlyBalance() const;
204 int64_t GetStake() const;
205 int64_t GetNewMint() const;
206 int64_t GetWatchOnlyStake() const;
207 int64_t GetWatchOnlyNewMint() const;
208 bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
209 bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
210 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
212 void GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight);
213 bool CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nTime, uint32_t nBits, CTransaction &txNew, CKey& key);
214 bool MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nMaxValue, std::list<uint256>& listMerged);
216 std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
218 bool NewKeyPool(unsigned int nSize = 0);
219 bool TopUpKeyPool(unsigned int nSize = 0);
220 int64_t AddReserveKey(const CKeyPool& keypool);
221 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
222 void KeepKey(int64_t nIndex);
223 void ReturnKey(int64_t nIndex);
224 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
225 int64_t GetOldestKeyPoolTime();
226 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
228 std::set< std::set<CBitcoinAddress> > GetAddressGroupings();
229 std::map<CBitcoinAddress, int64_t> GetAddressBalances();
231 isminetype IsMine(const CTxIn& txin) const;
232 int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
233 isminetype IsMine(const CTxOut& txout) const;
234 int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const;
235 bool IsChange(const CTxOut& txout) const;
236 int64_t GetChange(const CTxOut& txout) const;
237 bool IsMine(const CTransaction& tx) const;
238 bool IsFromMe(const CTransaction& tx) const;
239 int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const;
240 int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const;
241 int64_t GetChange(const CTransaction& tx) const;
242 void SetBestChain(const CBlockLocator& loc);
244 DBErrors LoadWallet(bool& fFirstRunRet);
245 DBErrors ZapWalletTx();
247 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
248 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
249 bool DelAddressBookName(const CBitcoinAddress& address);
250 void UpdatedTransaction(const uint256 &hashTx);
251 void PrintWallet(const CBlock& block);
252 void Inventory(const uint256 &hash);
254 unsigned int GetKeyPoolSize()
256 return (unsigned int)(setKeyPool.size());
259 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
260 bool SetDefaultKey(const CPubKey &vchPubKey);
262 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
263 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
265 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
266 bool SetMaxVersion(int nVersion);
268 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
269 int GetVersion() { return nWalletVersion; }
271 void FixSpentCoins(int& nMismatchSpent, int64_t& nBalanceInQuestion, bool fCheckOnly = false);
272 void DisableTransaction(const CTransaction &tx);
274 /** Address book entry changed.
275 * @note called with lock cs_wallet held.
277 boost::signals2::signal<void (CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
279 /** Wallet transaction added, removed or updated.
280 * @note called with lock cs_wallet held.
282 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
284 /** Watch-only address added */
285 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
288 /** A key allocated from the key pool. */
296 CReserveKey(CWallet* pwalletIn) : pwallet(pwalletIn), nIndex(-1) {}
305 CPubKey GetReservedKey();
310 typedef std::map<std::string, std::string> mapValue_t;
312 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
314 if (!mapValue.count("n"))
316 nOrderPos = -1; // TODO: calculate elsewhere
319 nOrderPos = strtoll(mapValue["n"]);
322 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
326 mapValue["n"] = i64tostr(nOrderPos);
330 // A transaction with a bunch of additional info that only the owner cares about.
331 // It includes any unrecorded transactions needed to link it back to the block chain.
333 class CWalletTx : public CMerkleTx
336 const CWallet* pwallet;
339 std::vector<CMerkleTx> vtxPrev;
341 std::vector<std::pair<std::string, std::string> > vOrderForm;
342 unsigned int fTimeReceivedIsTxTime;
343 unsigned int nTimeReceived; // time received by this node
344 unsigned int nTimeSmart;
346 std::string strFromAccount;
347 std::vector<char> vfSpent; // which outputs are already spent
348 int64_t nOrderPos; // position in ordered transaction list
351 mutable bool fDebitCached;
352 mutable bool fWatchDebitCached;
353 mutable bool fCreditCached;
354 mutable bool fWatchCreditCached;
355 mutable bool fAvailableCreditCached;
356 mutable bool fImmatureCreditCached;
357 mutable bool fImmatureWatchCreditCached;
358 mutable bool fAvailableWatchCreditCached;
359 mutable bool fChangeCached;
360 mutable int64_t nDebitCached;
361 mutable int64_t nWatchDebitCached;
362 mutable int64_t nCreditCached;
363 mutable int64_t nWatchCreditCached;
364 mutable int64_t nAvailableCreditCached;
365 mutable int64_t nImmatureCreditCached;
366 mutable int64_t nImmatureWatchCreditCached;
367 mutable int64_t nAvailableWatchCreditCached;
368 mutable int64_t nChangeCached;
371 CWalletTx(const CWallet* pwalletIn);
372 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn);
373 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn);
374 void Init(const CWallet* pwalletIn);
378 CWalletTx* pthis = const_cast<CWalletTx*>(this);
385 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
388 for(char f : vfSpent)
390 str += (f ? '1' : '0');
394 pthis->mapValue["spent"] = str;
396 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
399 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
402 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
405 READWRITE(vOrderForm);
406 READWRITE(fTimeReceivedIsTxTime);
407 READWRITE(nTimeReceived);
413 pthis->strFromAccount = pthis->mapValue["fromaccount"];
415 if (mapValue.count("spent"))
416 for(char c : pthis->mapValue["spent"])
417 pthis->vfSpent.push_back(c != '0');
419 pthis->vfSpent.assign(vout.size(), fSpent);
421 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
423 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)strtoll(pthis->mapValue["timesmart"]) : 0;
426 pthis->mapValue.erase("fromaccount");
427 pthis->mapValue.erase("version");
428 pthis->mapValue.erase("spent");
429 pthis->mapValue.erase("n");
430 pthis->mapValue.erase("timesmart");
433 // marks certain txout's as spent
434 // returns true if any update took place
435 bool UpdateSpent(const std::vector<char>& vfNewSpent);
437 // make sure balances are recalculated
439 void BindWallet(CWallet *pwalletIn);
440 void MarkSpent(unsigned int nOut);
441 void MarkUnspent(unsigned int nOut);
442 bool IsSpent(unsigned int nOut) const;
444 int64_t GetDebit(const isminefilter& filter) const;
445 int64_t GetCredit(const isminefilter& filter) const;
446 int64_t GetImmatureCredit(bool fUseCache=true) const;
447 int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const;
448 int64_t GetAvailableCredit(bool fUseCache=true) const;
449 int64_t GetAvailableWatchCredit(bool fUseCache=true) const;
450 int64_t GetChange() const;
452 void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
453 std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
455 void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
456 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
458 bool IsFromMe(const isminefilter& filter) const
460 return (GetDebit(filter) > 0);
463 bool InMempool() const;
464 bool IsTrusted() const;
468 int64_t GetTxTime() const;
469 int GetRequestCount() const;
471 void AddSupportingTransactions(CTxDB& txdb);
473 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
474 bool AcceptWalletTransaction();
476 bool RelayWalletTransaction(CTxDB& txdb);
477 bool RelayWalletTransaction();
491 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn) :
492 tx(txIn), i(iIn), nDepth(nDepthIn), fSpendable(fSpendableIn) {}
494 std::string ToString() const
496 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());
503 // Private key that includes an expiration date in case it never gets used.
508 int64_t nTimeCreated;
509 int64_t nTimeExpires;
510 std::string strComment;
511 //// todo: add something to note what created it (user, getnewaddress, change)
512 //// maybe should have a map<string, string> property map
514 CWalletKey(int64_t nExpires=0) : nTimeCreated(nExpires ? GetTime() : 0), nTimeExpires(nExpires) {}
518 if (!(nType & SER_GETHASH))
520 READWRITE(vchPrivKey);
521 READWRITE(nTimeCreated);
522 READWRITE(nTimeExpires);
523 READWRITE(strComment);
530 /** Account information.
531 * Stored in wallet with key "acc"+string account name.
545 vchPubKey = CPubKey();
550 if (!(nType & SER_GETHASH))
552 READWRITE(vchPubKey);
558 /** Internal transfers.
559 * Database key is acentry<account><counter>.
561 class CAccountingEntry
564 std::string strAccount = "";
565 int64_t nCreditDebit = 0;
567 std::string strOtherAccount = "";
568 std::string strComment = "";
570 int64_t nOrderPos = -1; // position in ordered transaction list
571 uint64_t nEntryNo = 0;
573 CAccountingEntry() { }
577 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
578 if (!(nType & SER_GETHASH))
580 // Note: strAccount is serialized as part of the key, not here.
581 READWRITE(nCreditDebit);
583 READWRITE(strOtherAccount);
587 WriteOrderPos(nOrderPos, me.mapValue);
589 if (!(mapValue.empty() && _ssExtra.empty()))
591 CDataStream ss(nType, nVersion);
592 ss.insert(ss.begin(), '\0');
594 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
595 me.strComment.append(ss.str());
599 READWRITE(strComment);
601 size_t nSepPos = strComment.find("\0", 0, 1);
605 if (std::string::npos != nSepPos)
607 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
609 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
611 ReadOrderPos(me.nOrderPos, me.mapValue);
613 if (std::string::npos != nSepPos)
614 me.strComment.erase(nSepPos);
616 me.mapValue.erase("n");
620 std::vector<char> _ssExtra;
623 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);