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 #include "ui_interface.h"
18 /** (client) version numbers for particular wallet features */
21 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
23 FEATURE_WALLETCRYPT = 40000, // wallet encryption
24 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
26 FEATURE_LATEST = 60000
30 /** A key pool entry */
35 std::vector<unsigned char> vchPubKey;
42 CKeyPool(const std::vector<unsigned char>& vchPubKeyIn)
45 vchPubKey = vchPubKeyIn;
50 if (!(nType & SER_GETHASH))
57 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
58 * and provides the ability to create new transactions.
60 class CWallet : public CCryptoKeyStore
63 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
64 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
66 CWalletDB *pwalletdbEncryption;
68 // the current wallet version: clients below this version are not able to load the wallet
71 // the maxmimum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
72 int nWalletMaxVersion;
75 mutable CCriticalSection cs_wallet;
78 std::string strWalletFile;
80 std::set<int64> setKeyPool;
83 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
84 MasterKeyMap mapMasterKeys;
85 unsigned int nMasterKeyMaxID;
89 nWalletVersion = FEATURE_BASE;
90 nWalletMaxVersion = FEATURE_BASE;
93 pwalletdbEncryption = NULL;
95 CWallet(std::string strWalletFileIn)
97 nWalletVersion = FEATURE_BASE;
98 nWalletMaxVersion = FEATURE_BASE;
99 strWalletFile = strWalletFileIn;
102 pwalletdbEncryption = NULL;
105 std::map<uint256, CWalletTx> mapWallet;
106 std::map<uint256, int> mapRequestCount;
108 std::map<CBitcoinAddress, std::string> mapAddressBook;
110 std::vector<unsigned char> vchDefaultKey;
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 // keystore implementation
116 // Generate a new key
117 std::vector<unsigned char> GenerateNewKey();
118 // Adds a key to the store, and saves it to disk.
119 bool AddKey(const CKey& key);
120 // Adds a key to the store, without saving it to disk (used by LoadWallet)
121 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
123 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
125 // Adds an encrypted key to the store, and saves it to disk.
126 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
127 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
128 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
129 bool AddCScript(const CScript& redeemScript);
130 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
132 bool Unlock(const SecureString& strWalletPassphrase);
133 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
134 bool EncryptWallet(const SecureString& strWalletPassphrase);
137 bool AddToWallet(const CWalletTx& wtxIn);
138 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
139 bool EraseFromWallet(uint256 hash);
140 void WalletUpdateSpent(const CTransaction& prevout);
141 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
142 int ScanForWalletTransaction(const uint256& hashTx);
143 void ReacceptWalletTransactions();
144 void ResendWalletTransactions();
145 int64 GetBalance() const;
146 int64 GetUnconfirmedBalance() const;
147 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
148 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
149 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
150 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
151 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
155 int64 AddReserveKey(const CKeyPool& keypool);
156 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
157 void KeepKey(int64 nIndex);
158 void ReturnKey(int64 nIndex);
159 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
160 int64 GetOldestKeyPoolTime();
161 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
163 bool IsMine(const CTxIn& txin) const;
164 int64 GetDebit(const CTxIn& txin) const;
165 bool IsMine(const CTxOut& txout) const
167 return ::IsMine(*this, txout.scriptPubKey);
169 int64 GetCredit(const CTxOut& txout) const
171 if (!MoneyRange(txout.nValue))
172 throw std::runtime_error("CWallet::GetCredit() : value out of range");
173 return (IsMine(txout) ? txout.nValue : 0);
175 bool IsChange(const CTxOut& txout) const;
176 int64 GetChange(const CTxOut& txout) const
178 if (!MoneyRange(txout.nValue))
179 throw std::runtime_error("CWallet::GetChange() : value out of range");
180 return (IsChange(txout) ? txout.nValue : 0);
182 bool IsMine(const CTransaction& tx) const
184 BOOST_FOREACH(const CTxOut& txout, tx.vout)
189 bool IsFromMe(const CTransaction& tx) const
191 return (GetDebit(tx) > 0);
193 int64 GetDebit(const CTransaction& tx) const
196 BOOST_FOREACH(const CTxIn& txin, tx.vin)
198 nDebit += GetDebit(txin);
199 if (!MoneyRange(nDebit))
200 throw std::runtime_error("CWallet::GetDebit() : value out of range");
204 int64 GetCredit(const CTransaction& tx) const
207 BOOST_FOREACH(const CTxOut& txout, tx.vout)
209 nCredit += GetCredit(txout);
210 if (!MoneyRange(nCredit))
211 throw std::runtime_error("CWallet::GetCredit() : value out of range");
215 int64 GetChange(const CTransaction& tx) const
218 BOOST_FOREACH(const CTxOut& txout, tx.vout)
220 nChange += GetChange(txout);
221 if (!MoneyRange(nChange))
222 throw std::runtime_error("CWallet::GetChange() : value out of range");
226 void SetBestChain(const CBlockLocator& loc);
228 int LoadWallet(bool& fFirstRunRet);
230 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
232 bool DelAddressBookName(const CBitcoinAddress& address);
234 void UpdatedTransaction(const uint256 &hashTx);
236 void PrintWallet(const CBlock& block);
238 void Inventory(const uint256 &hash)
242 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
243 if (mi != mapRequestCount.end())
250 return setKeyPool.size();
253 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
255 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
257 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
258 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
260 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
261 bool SetMaxVersion(int nVersion);
263 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
264 int GetVersion() { return nWalletVersion; }
266 /** Address book entry changed.
267 * @note called with lock cs_wallet held.
269 boost::signals2::signal<void (CWallet *wallet, const std::string &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
271 /** Wallet transaction added, removed or updated.
272 * @note called with lock cs_wallet held.
274 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
277 /** A key allocated from the key pool. */
283 std::vector<unsigned char> vchPubKey;
285 CReserveKey(CWallet* pwalletIn)
298 std::vector<unsigned char> GetReservedKey();
303 /** A transaction with a bunch of additional info that only the owner cares about.
304 * It includes any unrecorded transactions needed to link it back to the block chain.
306 class CWalletTx : public CMerkleTx
309 const CWallet* pwallet;
312 std::vector<CMerkleTx> vtxPrev;
313 std::map<std::string, std::string> mapValue;
314 std::vector<std::pair<std::string, std::string> > vOrderForm;
315 unsigned int fTimeReceivedIsTxTime;
316 unsigned int nTimeReceived; // time received by this node
318 std::string strFromAccount;
319 std::vector<char> vfSpent; // which outputs are already spent
322 mutable bool fDebitCached;
323 mutable bool fCreditCached;
324 mutable bool fAvailableCreditCached;
325 mutable bool fChangeCached;
326 mutable int64 nDebitCached;
327 mutable int64 nCreditCached;
328 mutable int64 nAvailableCreditCached;
329 mutable int64 nChangeCached;
336 CWalletTx(const CWallet* pwalletIn)
341 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
346 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
351 void Init(const CWallet* pwalletIn)
357 fTimeReceivedIsTxTime = false;
360 strFromAccount.clear();
362 fDebitCached = false;
363 fCreditCached = false;
364 fAvailableCreditCached = false;
365 fChangeCached = false;
368 nAvailableCreditCached = 0;
374 CWalletTx* pthis = const_cast<CWalletTx*>(this);
381 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
384 BOOST_FOREACH(char f, vfSpent)
386 str += (f ? '1' : '0');
390 pthis->mapValue["spent"] = str;
393 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
396 READWRITE(vOrderForm);
397 READWRITE(fTimeReceivedIsTxTime);
398 READWRITE(nTimeReceived);
404 pthis->strFromAccount = pthis->mapValue["fromaccount"];
406 if (mapValue.count("spent"))
407 BOOST_FOREACH(char c, pthis->mapValue["spent"])
408 pthis->vfSpent.push_back(c != '0');
410 pthis->vfSpent.assign(vout.size(), fSpent);
413 pthis->mapValue.erase("fromaccount");
414 pthis->mapValue.erase("version");
415 pthis->mapValue.erase("spent");
418 // marks certain txout's as spent
419 // returns true if any update took place
420 bool UpdateSpent(const std::vector<char>& vfNewSpent)
422 bool fReturn = false;
423 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
425 if (i == vfSpent.size())
428 if (vfNewSpent[i] && !vfSpent[i])
432 fAvailableCreditCached = false;
438 // make sure balances are recalculated
441 fCreditCached = false;
442 fAvailableCreditCached = false;
443 fDebitCached = false;
444 fChangeCached = false;
447 void BindWallet(CWallet *pwalletIn)
453 void MarkSpent(unsigned int nOut)
455 if (nOut >= vout.size())
456 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
457 vfSpent.resize(vout.size());
460 vfSpent[nOut] = true;
461 fAvailableCreditCached = false;
465 bool IsSpent(unsigned int nOut) const
467 if (nOut >= vout.size())
468 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
469 if (nOut >= vfSpent.size())
471 return (!!vfSpent[nOut]);
474 int64 GetDebit() const
480 nDebitCached = pwallet->GetDebit(*this);
485 int64 GetCredit(bool fUseCache=true) const
487 // Must wait until coinbase is safely deep enough in the chain before valuing it
488 if (IsCoinBase() && GetBlocksToMaturity() > 0)
491 // GetBalance can assume transactions in mapWallet won't change
492 if (fUseCache && fCreditCached)
493 return nCreditCached;
494 nCreditCached = pwallet->GetCredit(*this);
495 fCreditCached = true;
496 return nCreditCached;
499 int64 GetAvailableCredit(bool fUseCache=true) const
501 // Must wait until coinbase is safely deep enough in the chain before valuing it
502 if (IsCoinBase() && GetBlocksToMaturity() > 0)
505 if (fUseCache && fAvailableCreditCached)
506 return nAvailableCreditCached;
509 for (unsigned int i = 0; i < vout.size(); i++)
513 const CTxOut &txout = vout[i];
514 nCredit += pwallet->GetCredit(txout);
515 if (!MoneyRange(nCredit))
516 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
520 nAvailableCreditCached = nCredit;
521 fAvailableCreditCached = true;
526 int64 GetChange() const
529 return nChangeCached;
530 nChangeCached = pwallet->GetChange(*this);
531 fChangeCached = true;
532 return nChangeCached;
535 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
536 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
538 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
539 int64& nSent, int64& nFee) const;
541 bool IsFromMe() const
543 return (GetDebit() > 0);
546 bool IsConfirmed() const
548 // Quick answer in most cases
551 if (GetDepthInMainChain() >= 1)
553 if (!IsFromMe()) // using wtx's cached debit
556 // If no confirmations but it's from us, we can still
557 // consider it confirmed if all dependencies are confirmed
558 std::map<uint256, const CMerkleTx*> mapPrev;
559 std::vector<const CMerkleTx*> vWorkQueue;
560 vWorkQueue.reserve(vtxPrev.size()+1);
561 vWorkQueue.push_back(this);
562 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
564 const CMerkleTx* ptx = vWorkQueue[i];
568 if (ptx->GetDepthInMainChain() >= 1)
570 if (!pwallet->IsFromMe(*ptx))
575 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
576 mapPrev[tx.GetHash()] = &tx;
579 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
581 if (!mapPrev.count(txin.prevout.hash))
583 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
591 int64 GetTxTime() const;
592 int GetRequestCount() const;
594 void AddSupportingTransactions(CTxDB& txdb);
596 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
597 bool AcceptWalletTransaction();
599 void RelayWalletTransaction(CTxDB& txdb);
600 void RelayWalletTransaction();
604 /** Private key that includes an expiration date in case it never gets used. */
611 std::string strComment;
612 //// todo: add something to note what created it (user, getnewaddress, change)
613 //// maybe should have a map<string, string> property map
615 CWalletKey(int64 nExpires=0)
617 nTimeCreated = (nExpires ? GetTime() : 0);
618 nTimeExpires = nExpires;
623 if (!(nType & SER_GETHASH))
625 READWRITE(vchPrivKey);
626 READWRITE(nTimeCreated);
627 READWRITE(nTimeExpires);
628 READWRITE(strComment);
637 /** Account information.
638 * Stored in wallet with key "acc"+string account name.
643 std::vector<unsigned char> vchPubKey;
657 if (!(nType & SER_GETHASH))
659 READWRITE(vchPubKey);
665 /** Internal transfers.
666 * Database key is acentry<account><counter>.
668 class CAccountingEntry
671 std::string strAccount;
674 std::string strOtherAccount;
675 std::string strComment;
687 strOtherAccount.clear();
693 if (!(nType & SER_GETHASH))
695 // Note: strAccount is serialized as part of the key, not here.
696 READWRITE(nCreditDebit);
698 READWRITE(strOtherAccount);
699 READWRITE(strComment);
703 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);