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
12 extern unsigned int nStakeMaxAge;
13 extern bool fWalletUnlockMintOnly;
14 extern bool fConfChange;
15 class CAccountingEntry;
21 // Set of selected transactions
22 typedef std::set<std::pair<const CWalletTx*,unsigned int> > CoinsSet;
24 /** (client) version numbers for particular wallet features */
27 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
29 FEATURE_WALLETCRYPT = 40000, // wallet encryption
30 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
31 FEATURE_MALLKEY = 60017,
32 FEATURE_LATEST = 60017
35 /** A key pool entry */
44 CKeyPool(const CPubKey& vchPubKeyIn);
48 if (!(nType & SER_GETHASH))
55 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
56 * and provides the ability to create new transactions.
58 class CWallet : public CCryptoKeyStore
61 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;
63 CWalletDB *pwalletdbEncryption, *pwalletdbDecryption;
65 // the current wallet version: clients below this version are not able to load the wallet
68 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
69 int nWalletMaxVersion;
74 // stake mining statistics
75 uint64_t nKernelsTried;
76 uint64_t nCoinDaysTried;
79 mutable CCriticalSection cs_wallet;
82 std::string strWalletFile;
84 std::set<int64_t> setKeyPool;
86 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
87 std::map<CMalleableKeyView, CKeyMetadata> mapMalleableKeyMetadata;
90 std::map<CBitcoinAddress, CKeyMetadata> mapKeyMetadata;
92 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
93 MasterKeyMap mapMasterKeys;
94 unsigned int nMasterKeyMaxID;
97 CWallet(std::string strWalletFileIn);
100 std::map<uint256, CWalletTx> mapWallet;
101 std::vector<uint256> vMintingWalletUpdated;
102 int64_t nOrderPosNext;
103 std::map<uint256, int> mapRequestCount;
105 std::map<CBitcoinAddress, std::string> mapAddressBook;
107 CPubKey vchDefaultKey;
108 int64_t nTimeFirstKey;
110 const CWalletTx* GetWalletTx(const uint256& hash) const;
112 // check whether we are allowed to upgrade (or already support) to the named feature
113 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
115 void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const;
116 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
117 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;
119 // Simple select (without randomization)
120 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;
122 // keystore implementation
123 // Generate a new key
124 CPubKey GenerateNewKey();
125 CMalleableKeyView GenerateNewMalleableKey();
126 // Adds a key to the store, and saves it to disk.
127 bool AddKey(const CKey& key);
128 bool AddKey(const CMalleableKey& mKey);
129 // Adds a key to the store, without saving it to disk (used by LoadWallet)
130 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
131 // Load metadata (used by LoadWallet)
132 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
133 bool LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata);
135 // Load malleable key without saving it to disk (used by LoadWallet)
136 bool LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH);
137 bool LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH);
139 bool LoadMinVersion(int nVersion);
141 // Adds an encrypted key to the store, and saves it to disk.
142 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
143 bool AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH);
144 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
145 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
146 bool AddCScript(const CScript& redeemScript);
147 bool LoadCScript(const CScript& redeemScript);
149 // Adds a watch-only address to the store, and saves it to disk.
150 bool AddWatchOnly(const CScript &dest);
151 bool RemoveWatchOnly(const CScript &dest);
152 // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
153 bool LoadWatchOnly(const CScript &dest);
155 bool Unlock(const SecureString& strWalletPassphrase);
156 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
157 bool EncryptWallet(const SecureString& strWalletPassphrase);
158 bool DecryptWallet(const SecureString& strWalletPassphrase);
160 void GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const;
163 /** Increment the next transaction order id
164 @return next transaction order id
166 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
168 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
169 typedef std::multimap<int64_t, TxPair > TxItems;
171 /** Get the wallet's activity log
172 @return multimap of ordered transactions and accounting entries
173 @warning Returned pointers are *only* valid within the scope of passed acentries
175 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
178 bool AddToWallet(const CWalletTx& wtxIn);
179 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
180 bool EraseFromWallet(uint256 hash);
182 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
183 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
184 int ScanForWalletTransaction(const uint256& hashTx);
185 void ReacceptWalletTransactions();
186 void ResendWalletTransactions(int64_t nBestBlockTime);
187 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
188 int64_t GetBalance() const;
189 int64_t GetWatchOnlyBalance() const;
190 int64_t GetUnconfirmedBalance() const;
191 int64_t GetUnconfirmedWatchOnlyBalance() const;
192 int64_t GetImmatureBalance() const;
193 int64_t GetImmatureWatchOnlyBalance() const;
194 int64_t GetStake() const;
195 int64_t GetNewMint() const;
196 int64_t GetWatchOnlyStake() const;
197 int64_t GetWatchOnlyNewMint() const;
198 bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
199 bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
200 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
202 void GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight);
203 bool CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nTime, uint32_t nBits, CTransaction &txNew, CKey& key);
204 bool MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nMaxValue, std::list<uint256>& listMerged);
206 std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
208 bool NewKeyPool(unsigned int nSize = 0);
209 bool TopUpKeyPool(unsigned int nSize = 0);
210 int64_t AddReserveKey(const CKeyPool& keypool);
211 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
212 void KeepKey(int64_t nIndex);
213 void ReturnKey(int64_t nIndex);
214 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
215 int64_t GetOldestKeyPoolTime();
216 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
218 std::set< std::set<CBitcoinAddress> > GetAddressGroupings();
219 std::map<CBitcoinAddress, int64_t> GetAddressBalances();
221 isminetype IsMine(const CTxIn& txin) const;
222 int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
223 isminetype IsMine(const CTxOut& txout) const;
224 int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const;
225 bool IsChange(const CTxOut& txout) const;
226 int64_t GetChange(const CTxOut& txout) const;
227 bool IsMine(const CTransaction& tx) const;
228 bool IsFromMe(const CTransaction& tx) const;
229 int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const;
230 int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const;
231 int64_t GetChange(const CTransaction& tx) const;
232 void SetBestChain(const CBlockLocator& loc);
234 DBErrors LoadWallet(bool& fFirstRunRet);
235 DBErrors ZapWalletTx();
237 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
238 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
239 bool DelAddressBookName(const CBitcoinAddress& address);
240 void UpdatedTransaction(const uint256 &hashTx);
241 void PrintWallet(const CBlock& block);
243 void Inventory(const uint256 &hash);
245 unsigned int GetKeyPoolSize();
247 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
248 bool SetDefaultKey(const CPubKey &vchPubKey);
250 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
251 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
253 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
254 bool SetMaxVersion(int nVersion);
256 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
257 int GetVersion() { return nWalletVersion; }
259 void FixSpentCoins(int& nMismatchSpent, int64_t& nBalanceInQuestion, bool fCheckOnly = false);
260 void DisableTransaction(const CTransaction &tx);
262 /** Address book entry changed.
263 * @note called with lock cs_wallet held.
265 boost::signals2::signal<void (CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
267 /** Wallet transaction added, removed or updated.
268 * @note called with lock cs_wallet held.
270 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
272 /** Watch-only address added */
273 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
276 /** A key allocated from the key pool. */
284 CReserveKey(CWallet* pwalletIn);
289 CPubKey GetReservedKey();
294 typedef std::map<std::string, std::string> mapValue_t;
297 /** A transaction with a bunch of additional info that only the owner cares about.
298 * It includes any unrecorded transactions needed to link it back to the block chain.
300 class CWalletTx : public CMerkleTx
303 const CWallet* pwallet;
306 std::vector<CMerkleTx> vtxPrev;
308 std::vector<std::pair<std::string, std::string> > vOrderForm;
309 unsigned int fTimeReceivedIsTxTime;
310 unsigned int nTimeReceived; // time received by this node
311 unsigned int nTimeSmart;
313 std::string strFromAccount;
314 std::vector<char> vfSpent; // which outputs are already spent
315 int64_t nOrderPos; // position in ordered transaction list
318 mutable bool fDebitCached;
319 mutable bool fWatchDebitCached;
320 mutable bool fCreditCached;
321 mutable bool fWatchCreditCached;
322 mutable bool fAvailableCreditCached;
323 mutable bool fImmatureCreditCached;
324 mutable bool fImmatureWatchCreditCached;
325 mutable bool fAvailableWatchCreditCached;
326 mutable bool fChangeCached;
327 mutable int64_t nDebitCached;
328 mutable int64_t nWatchDebitCached;
329 mutable int64_t nCreditCached;
330 mutable int64_t nWatchCreditCached;
331 mutable int64_t nAvailableCreditCached;
332 mutable int64_t nImmatureCreditCached;
333 mutable int64_t nImmatureWatchCreditCached;
334 mutable int64_t nAvailableWatchCreditCached;
335 mutable int64_t nChangeCached;
338 CWalletTx(const CWallet* pwalletIn);
339 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn);
340 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn);
342 void Init(const CWallet* pwalletIn);
346 CWalletTx* pthis = const_cast<CWalletTx*>(this);
353 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
356 for (char f : vfSpent)
358 str += (f ? '1' : '0');
362 pthis->mapValue["spent"] = str;
364 if (pthis->nOrderPos != -1)
365 pthis->mapValue["n"] = i64tostr(pthis->nOrderPos);
368 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
371 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
374 READWRITE(vOrderForm);
375 READWRITE(fTimeReceivedIsTxTime);
376 READWRITE(nTimeReceived);
382 pthis->strFromAccount = pthis->mapValue["fromaccount"];
384 if (mapValue.count("spent"))
385 for (char c : pthis->mapValue["spent"])
386 pthis->vfSpent.push_back(c != '0');
388 pthis->vfSpent.assign(vout.size(), fSpent);
390 const auto it_op = pthis->mapValue.find("n");
391 pthis->nOrderPos = (it_op != pthis->mapValue.end()) ? atoi64(it_op->second.c_str()) : -1;
393 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
396 pthis->mapValue.erase("fromaccount");
397 pthis->mapValue.erase("version");
398 pthis->mapValue.erase("spent");
399 pthis->mapValue.erase("n");
400 pthis->mapValue.erase("timesmart");
403 // marks certain txout's as spent
404 // returns true if any update took place
405 bool UpdateSpent(const std::vector<char>& vfNewSpent);
407 // make sure balances are recalculated
409 void BindWallet(CWallet *pwalletIn);
410 void MarkSpent(unsigned int nOut);
411 void MarkUnspent(unsigned int nOut);
412 bool IsSpent(unsigned int nOut) const;
414 int64_t GetDebit(const isminefilter& filter) const;
415 int64_t GetCredit(const isminefilter& filter) const;
416 int64_t GetImmatureCredit(bool fUseCache=true) const;
417 int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const;
418 int64_t GetAvailableCredit(bool fUseCache=true) const;
419 int64_t GetAvailableWatchCredit(bool fUseCache=true) const;
420 int64_t GetChange() const;
422 void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
423 std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
425 void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
426 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
428 bool IsFromMe(const isminefilter& filter) const;
430 bool InMempool() const;
431 bool IsTrusted() const;
435 int64_t GetTxTime() const;
436 int GetRequestCount() const;
438 void AddSupportingTransactions(CTxDB& txdb);
440 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
441 bool AcceptWalletTransaction();
443 bool RelayWalletTransaction(CTxDB& txdb);
444 bool RelayWalletTransaction();
458 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn);
460 std::string ToString() const;
466 /** Private key that includes an expiration date in case it never gets used. */
471 int64_t nTimeCreated;
472 int64_t nTimeExpires;
473 std::string strComment;
474 //// todo: add something to note what created it (user, getnewaddress, change)
475 //// maybe should have a map<string, string> property map
477 CWalletKey(int64_t nExpires=0);
481 if (!(nType & SER_GETHASH))
483 READWRITE(vchPrivKey);
484 READWRITE(nTimeCreated);
485 READWRITE(nTimeExpires);
486 READWRITE(strComment);
495 /** Account information.
496 * Stored in wallet with key "acc"+string account name.
509 if (!(nType & SER_GETHASH))
511 READWRITE(vchPubKey);
517 /** Internal transfers.
518 * Database key is acentry<account><counter>.
520 class CAccountingEntry
523 std::string strAccount;
524 int64_t nCreditDebit;
526 std::string strOtherAccount;
527 std::string strComment;
529 int64_t nOrderPos; // position in ordered transaction list
538 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
539 if (!(nType & SER_GETHASH))
541 // Note: strAccount is serialized as part of the key, not here.
542 READWRITE(nCreditDebit);
544 READWRITE(strOtherAccount);
549 me.mapValue["n"] = i64tostr(nOrderPos);
551 if (!(mapValue.empty() && _ssExtra.empty()))
553 CDataStream ss(nType, nVersion);
554 ss.insert(ss.begin(), '\0');
556 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
557 me.strComment.append(ss.str());
561 READWRITE(strComment);
563 size_t nSepPos = strComment.find("\0", 0, 1);
567 if (std::string::npos != nSepPos)
569 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
571 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
573 const auto it_op = me.mapValue.find("n");
574 me.nOrderPos = (it_op != me.mapValue.end()) ? atoi64(it_op->second.c_str()) : -1;
576 if (std::string::npos != nSepPos)
577 me.strComment.erase(nSepPos);
579 me.mapValue.erase("n");
583 std::vector<char> _ssExtra;
586 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);