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 license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_WALLET_H
6 #define BITCOIN_WALLET_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::vector<uint256> vWalletUpdated;
108 std::map<uint256, int> mapRequestCount;
110 std::map<CBitcoinAddress, std::string> mapAddressBook;
112 std::vector<unsigned char> vchDefaultKey;
114 // check whether we are allowed to upgrade (or already support) to the named feature
115 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
117 // keystore implementation
118 // Generate a new key
119 std::vector<unsigned char> GenerateNewKey();
120 // Adds a key to the store, and saves it to disk.
121 bool AddKey(const CKey& key);
122 // Adds a key to the store, without saving it to disk (used by LoadWallet)
123 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
125 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
127 // Adds an encrypted key to the store, and saves it to disk.
128 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
129 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
130 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
131 bool AddCScript(const CScript& redeemScript);
132 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
134 bool Unlock(const SecureString& strWalletPassphrase);
135 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
136 bool EncryptWallet(const SecureString& strWalletPassphrase);
139 bool AddToWallet(const CWalletTx& wtxIn);
140 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
141 bool EraseFromWallet(uint256 hash);
142 void WalletUpdateSpent(const CTransaction& prevout);
143 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
144 int ScanForWalletTransaction(const uint256& hashTx);
145 void ReacceptWalletTransactions();
146 void ResendWalletTransactions();
147 int64 GetBalance() const;
148 int64 GetUnconfirmedBalance() const;
149 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
150 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
151 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
152 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
153 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
157 int64 AddReserveKey(const CKeyPool& keypool);
158 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
159 void KeepKey(int64 nIndex);
160 void ReturnKey(int64 nIndex);
161 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
162 int64 GetOldestKeyPoolTime();
163 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
165 bool IsMine(const CTxIn& txin) const;
166 int64 GetDebit(const CTxIn& txin) const;
167 bool IsMine(const CTxOut& txout) const
169 return ::IsMine(*this, txout.scriptPubKey);
171 int64 GetCredit(const CTxOut& txout) const
173 if (!MoneyRange(txout.nValue))
174 throw std::runtime_error("CWallet::GetCredit() : value out of range");
175 return (IsMine(txout) ? txout.nValue : 0);
177 bool IsChange(const CTxOut& txout) const;
178 int64 GetChange(const CTxOut& txout) const
180 if (!MoneyRange(txout.nValue))
181 throw std::runtime_error("CWallet::GetChange() : value out of range");
182 return (IsChange(txout) ? txout.nValue : 0);
184 bool IsMine(const CTransaction& tx) const
186 BOOST_FOREACH(const CTxOut& txout, tx.vout)
191 bool IsFromMe(const CTransaction& tx) const
193 return (GetDebit(tx) > 0);
195 int64 GetDebit(const CTransaction& tx) const
198 BOOST_FOREACH(const CTxIn& txin, tx.vin)
200 nDebit += GetDebit(txin);
201 if (!MoneyRange(nDebit))
202 throw std::runtime_error("CWallet::GetDebit() : value out of range");
206 int64 GetCredit(const CTransaction& tx) const
209 BOOST_FOREACH(const CTxOut& txout, tx.vout)
211 nCredit += GetCredit(txout);
212 if (!MoneyRange(nCredit))
213 throw std::runtime_error("CWallet::GetCredit() : value out of range");
217 int64 GetChange(const CTransaction& tx) const
220 BOOST_FOREACH(const CTxOut& txout, tx.vout)
222 nChange += GetChange(txout);
223 if (!MoneyRange(nChange))
224 throw std::runtime_error("CWallet::GetChange() : value out of range");
228 void SetBestChain(const CBlockLocator& loc);
230 int LoadWallet(bool& fFirstRunRet);
231 // bool BackupWallet(const std::string& strDest);
233 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
235 bool DelAddressBookName(const CBitcoinAddress& address);
237 void UpdatedTransaction(const uint256 &hashTx)
241 vWalletUpdated.push_back(hashTx);
245 void PrintWallet(const CBlock& block);
247 void Inventory(const uint256 &hash)
251 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
252 if (mi != mapRequestCount.end())
259 return setKeyPool.size();
262 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
264 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
266 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
267 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
269 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
270 bool SetMaxVersion(int nVersion);
272 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
273 int GetVersion() { return nWalletVersion; }
276 /** A key allocated from the key pool. */
282 std::vector<unsigned char> vchPubKey;
284 CReserveKey(CWallet* pwalletIn)
297 std::vector<unsigned char> GetReservedKey();
302 /** A transaction with a bunch of additional info that only the owner cares about.
303 * It includes any unrecorded transactions needed to link it back to the block chain.
305 class CWalletTx : public CMerkleTx
308 const CWallet* pwallet;
311 std::vector<CMerkleTx> vtxPrev;
312 std::map<std::string, std::string> mapValue;
313 std::vector<std::pair<std::string, std::string> > vOrderForm;
314 unsigned int fTimeReceivedIsTxTime;
315 unsigned int nTimeReceived; // time received by this node
317 std::string strFromAccount;
318 std::vector<char> vfSpent; // which outputs are already spent
321 mutable char fDebitCached;
322 mutable char fCreditCached;
323 mutable char fAvailableCreditCached;
324 mutable char fChangeCached;
325 mutable int64 nDebitCached;
326 mutable int64 nCreditCached;
327 mutable int64 nAvailableCreditCached;
328 mutable int64 nChangeCached;
330 // memory only UI hints
331 mutable unsigned int nTimeDisplayed;
332 mutable int nLinesDisplayed;
333 mutable char fConfirmedDisplayed;
340 CWalletTx(const CWallet* pwalletIn)
345 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
350 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
355 void Init(const CWallet* pwalletIn)
361 fTimeReceivedIsTxTime = false;
364 strFromAccount.clear();
366 fDebitCached = false;
367 fCreditCached = false;
368 fAvailableCreditCached = false;
369 fChangeCached = false;
372 nAvailableCreditCached = 0;
376 fConfirmedDisplayed = false;
381 CWalletTx* pthis = const_cast<CWalletTx*>(this);
388 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
391 BOOST_FOREACH(char f, vfSpent)
393 str += (f ? '1' : '0');
397 pthis->mapValue["spent"] = str;
400 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
403 READWRITE(vOrderForm);
404 READWRITE(fTimeReceivedIsTxTime);
405 READWRITE(nTimeReceived);
411 pthis->strFromAccount = pthis->mapValue["fromaccount"];
413 if (mapValue.count("spent"))
414 BOOST_FOREACH(char c, pthis->mapValue["spent"])
415 pthis->vfSpent.push_back(c != '0');
417 pthis->vfSpent.assign(vout.size(), fSpent);
420 pthis->mapValue.erase("fromaccount");
421 pthis->mapValue.erase("version");
422 pthis->mapValue.erase("spent");
425 // marks certain txout's as spent
426 // returns true if any update took place
427 bool UpdateSpent(const std::vector<char>& vfNewSpent)
429 bool fReturn = false;
430 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
432 if (i == vfSpent.size())
435 if (vfNewSpent[i] && !vfSpent[i])
439 fAvailableCreditCached = false;
445 // make sure balances are recalculated
448 fCreditCached = false;
449 fAvailableCreditCached = false;
450 fDebitCached = false;
451 fChangeCached = false;
454 void BindWallet(CWallet *pwalletIn)
460 void MarkSpent(unsigned int nOut)
462 if (nOut >= vout.size())
463 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
464 vfSpent.resize(vout.size());
467 vfSpent[nOut] = true;
468 fAvailableCreditCached = false;
472 bool IsSpent(unsigned int nOut) const
474 if (nOut >= vout.size())
475 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
476 if (nOut >= vfSpent.size())
478 return (!!vfSpent[nOut]);
481 int64 GetDebit() const
487 nDebitCached = pwallet->GetDebit(*this);
492 int64 GetCredit(bool fUseCache=true) const
494 // Must wait until coinbase is safely deep enough in the chain before valuing it
495 if (IsCoinBase() && GetBlocksToMaturity() > 0)
498 // GetBalance can assume transactions in mapWallet won't change
499 if (fUseCache && fCreditCached)
500 return nCreditCached;
501 nCreditCached = pwallet->GetCredit(*this);
502 fCreditCached = true;
503 return nCreditCached;
506 int64 GetAvailableCredit(bool fUseCache=true) const
508 // Must wait until coinbase is safely deep enough in the chain before valuing it
509 if (IsCoinBase() && GetBlocksToMaturity() > 0)
512 if (fUseCache && fAvailableCreditCached)
513 return nAvailableCreditCached;
516 for (unsigned int i = 0; i < vout.size(); i++)
520 const CTxOut &txout = vout[i];
521 nCredit += pwallet->GetCredit(txout);
522 if (!MoneyRange(nCredit))
523 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
527 nAvailableCreditCached = nCredit;
528 fAvailableCreditCached = true;
533 int64 GetChange() const
536 return nChangeCached;
537 nChangeCached = pwallet->GetChange(*this);
538 fChangeCached = true;
539 return nChangeCached;
542 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
543 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
545 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
546 int64& nSent, int64& nFee) const;
548 bool IsFromMe() const
550 return (GetDebit() > 0);
553 bool IsConfirmed() const
555 // Quick answer in most cases
558 if (GetDepthInMainChain() >= 1)
560 if (!IsFromMe()) // using wtx's cached debit
563 // If no confirmations but it's from us, we can still
564 // consider it confirmed if all dependencies are confirmed
565 std::map<uint256, const CMerkleTx*> mapPrev;
566 std::vector<const CMerkleTx*> vWorkQueue;
567 vWorkQueue.reserve(vtxPrev.size()+1);
568 vWorkQueue.push_back(this);
569 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
571 const CMerkleTx* ptx = vWorkQueue[i];
575 if (ptx->GetDepthInMainChain() >= 1)
577 if (!pwallet->IsFromMe(*ptx))
582 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
583 mapPrev[tx.GetHash()] = &tx;
586 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
588 if (!mapPrev.count(txin.prevout.hash))
590 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
598 int64 GetTxTime() const;
599 int GetRequestCount() const;
601 void AddSupportingTransactions(CTxDB& txdb);
603 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
604 bool AcceptWalletTransaction();
606 void RelayWalletTransaction(CTxDB& txdb);
607 void RelayWalletTransaction();
611 /** Private key that includes an expiration date in case it never gets used. */
618 std::string strComment;
619 //// todo: add something to note what created it (user, getnewaddress, change)
620 //// maybe should have a map<string, string> property map
622 CWalletKey(int64 nExpires=0)
624 nTimeCreated = (nExpires ? GetTime() : 0);
625 nTimeExpires = nExpires;
630 if (!(nType & SER_GETHASH))
632 READWRITE(vchPrivKey);
633 READWRITE(nTimeCreated);
634 READWRITE(nTimeExpires);
635 READWRITE(strComment);
644 /** Account information.
645 * Stored in wallet with key "acc"+string account name.
650 std::vector<unsigned char> vchPubKey;
664 if (!(nType & SER_GETHASH))
666 READWRITE(vchPubKey);
672 /** Internal transfers.
673 * Database key is acentry<account><counter>.
675 class CAccountingEntry
678 std::string strAccount;
681 std::string strOtherAccount;
682 std::string strComment;
694 strOtherAccount.clear();
700 if (!(nType & SER_GETHASH))
702 // Note: strAccount is serialized as part of the key, not here.
703 READWRITE(nCreditDebit);
705 READWRITE(strOtherAccount);
706 READWRITE(strComment);
710 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);