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
17 /** (client) version numbers for particular wallet features */
20 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
22 FEATURE_WALLETCRYPT = 40000, // wallet encryption
23 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
25 FEATURE_LATEST = 60000
29 /** A key pool entry */
34 std::vector<unsigned char> vchPubKey;
41 CKeyPool(const std::vector<unsigned char>& vchPubKeyIn)
44 vchPubKey = vchPubKeyIn;
49 if (!(nType & SER_GETHASH))
56 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
57 * and provides the ability to create new transactions.
59 class CWallet : public CCryptoKeyStore
62 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
63 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
65 CWalletDB *pwalletdbEncryption;
67 // the current wallet version: clients below this version are not able to load the wallet
70 // the maxmimum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
71 int nWalletMaxVersion;
74 mutable CCriticalSection cs_wallet;
77 std::string strWalletFile;
79 std::set<int64> setKeyPool;
82 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
83 MasterKeyMap mapMasterKeys;
84 unsigned int nMasterKeyMaxID;
88 nWalletVersion = FEATURE_BASE;
89 nWalletMaxVersion = FEATURE_BASE;
92 pwalletdbEncryption = NULL;
94 CWallet(std::string strWalletFileIn)
96 nWalletVersion = FEATURE_BASE;
97 nWalletMaxVersion = FEATURE_BASE;
98 strWalletFile = strWalletFileIn;
101 pwalletdbEncryption = NULL;
104 std::map<uint256, CWalletTx> mapWallet;
105 std::vector<uint256> vWalletUpdated;
107 std::map<uint256, int> mapRequestCount;
109 std::map<CBitcoinAddress, std::string> mapAddressBook;
111 std::vector<unsigned char> vchDefaultKey;
113 // check whether we are allowed to upgrade (or already support) to the named feature
114 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
116 // keystore implementation
117 // Generate a new key
118 std::vector<unsigned char> GenerateNewKey();
119 // Adds a key to the store, and saves it to disk.
120 bool AddKey(const CKey& key);
121 // Adds a key to the store, without saving it to disk (used by LoadWallet)
122 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
124 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
126 // Adds an encrypted key to the store, and saves it to disk.
127 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
128 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
129 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
130 bool AddCScript(const CScript& redeemScript);
131 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
133 bool Unlock(const SecureString& strWalletPassphrase);
134 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
135 bool EncryptWallet(const SecureString& strWalletPassphrase);
138 bool AddToWallet(const CWalletTx& wtxIn);
139 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
140 bool EraseFromWallet(uint256 hash);
141 void WalletUpdateSpent(const CTransaction& prevout);
142 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
143 int ScanForWalletTransaction(const uint256& hashTx);
144 void ReacceptWalletTransactions();
145 void ResendWalletTransactions();
146 int64 GetBalance() const;
147 int64 GetUnconfirmedBalance() const;
148 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
149 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
150 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
151 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
152 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
156 int64 AddReserveKey(const CKeyPool& keypool);
157 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
158 void KeepKey(int64 nIndex);
159 void ReturnKey(int64 nIndex);
160 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
161 int64 GetOldestKeyPoolTime();
162 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
164 bool IsMine(const CTxIn& txin) const;
165 int64 GetDebit(const CTxIn& txin) const;
166 bool IsMine(const CTxOut& txout) const
168 return ::IsMine(*this, txout.scriptPubKey);
170 int64 GetCredit(const CTxOut& txout) const
172 if (!MoneyRange(txout.nValue))
173 throw std::runtime_error("CWallet::GetCredit() : value out of range");
174 return (IsMine(txout) ? txout.nValue : 0);
176 bool IsChange(const CTxOut& txout) const;
177 int64 GetChange(const CTxOut& txout) const
179 if (!MoneyRange(txout.nValue))
180 throw std::runtime_error("CWallet::GetChange() : value out of range");
181 return (IsChange(txout) ? txout.nValue : 0);
183 bool IsMine(const CTransaction& tx) const
185 BOOST_FOREACH(const CTxOut& txout, tx.vout)
190 bool IsFromMe(const CTransaction& tx) const
192 return (GetDebit(tx) > 0);
194 int64 GetDebit(const CTransaction& tx) const
197 BOOST_FOREACH(const CTxIn& txin, tx.vin)
199 nDebit += GetDebit(txin);
200 if (!MoneyRange(nDebit))
201 throw std::runtime_error("CWallet::GetDebit() : value out of range");
205 int64 GetCredit(const CTransaction& tx) const
208 BOOST_FOREACH(const CTxOut& txout, tx.vout)
210 nCredit += GetCredit(txout);
211 if (!MoneyRange(nCredit))
212 throw std::runtime_error("CWallet::GetCredit() : value out of range");
216 int64 GetChange(const CTransaction& tx) const
219 BOOST_FOREACH(const CTxOut& txout, tx.vout)
221 nChange += GetChange(txout);
222 if (!MoneyRange(nChange))
223 throw std::runtime_error("CWallet::GetChange() : value out of range");
227 void SetBestChain(const CBlockLocator& loc);
229 int LoadWallet(bool& fFirstRunRet);
230 // bool BackupWallet(const std::string& strDest);
232 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
234 bool DelAddressBookName(const CBitcoinAddress& address);
236 void UpdatedTransaction(const uint256 &hashTx)
240 vWalletUpdated.push_back(hashTx);
244 void PrintWallet(const CBlock& block);
246 void Inventory(const uint256 &hash)
250 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
251 if (mi != mapRequestCount.end())
258 return setKeyPool.size();
261 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
263 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
265 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
266 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
268 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
269 bool SetMaxVersion(int nVersion);
271 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
272 int GetVersion() { return nWalletVersion; }
275 /** A key allocated from the key pool. */
281 std::vector<unsigned char> vchPubKey;
283 CReserveKey(CWallet* pwalletIn)
296 std::vector<unsigned char> GetReservedKey();
301 /** A transaction with a bunch of additional info that only the owner cares about.
302 * It includes any unrecorded transactions needed to link it back to the block chain.
304 class CWalletTx : public CMerkleTx
307 const CWallet* pwallet;
310 std::vector<CMerkleTx> vtxPrev;
311 std::map<std::string, std::string> mapValue;
312 std::vector<std::pair<std::string, std::string> > vOrderForm;
313 unsigned int fTimeReceivedIsTxTime;
314 unsigned int nTimeReceived; // time received by this node
316 std::string strFromAccount;
317 std::vector<char> vfSpent; // which outputs are already spent
320 mutable bool fDebitCached;
321 mutable bool fCreditCached;
322 mutable bool fAvailableCreditCached;
323 mutable bool fChangeCached;
324 mutable int64 nDebitCached;
325 mutable int64 nCreditCached;
326 mutable int64 nAvailableCreditCached;
327 mutable int64 nChangeCached;
334 CWalletTx(const CWallet* pwalletIn)
339 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
344 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
349 void Init(const CWallet* pwalletIn)
355 fTimeReceivedIsTxTime = false;
358 strFromAccount.clear();
360 fDebitCached = false;
361 fCreditCached = false;
362 fAvailableCreditCached = false;
363 fChangeCached = false;
366 nAvailableCreditCached = 0;
372 CWalletTx* pthis = const_cast<CWalletTx*>(this);
379 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
382 BOOST_FOREACH(char f, vfSpent)
384 str += (f ? '1' : '0');
388 pthis->mapValue["spent"] = str;
391 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
394 READWRITE(vOrderForm);
395 READWRITE(fTimeReceivedIsTxTime);
396 READWRITE(nTimeReceived);
402 pthis->strFromAccount = pthis->mapValue["fromaccount"];
404 if (mapValue.count("spent"))
405 BOOST_FOREACH(char c, pthis->mapValue["spent"])
406 pthis->vfSpent.push_back(c != '0');
408 pthis->vfSpent.assign(vout.size(), fSpent);
411 pthis->mapValue.erase("fromaccount");
412 pthis->mapValue.erase("version");
413 pthis->mapValue.erase("spent");
416 // marks certain txout's as spent
417 // returns true if any update took place
418 bool UpdateSpent(const std::vector<char>& vfNewSpent)
420 bool fReturn = false;
421 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
423 if (i == vfSpent.size())
426 if (vfNewSpent[i] && !vfSpent[i])
430 fAvailableCreditCached = false;
436 // make sure balances are recalculated
439 fCreditCached = false;
440 fAvailableCreditCached = false;
441 fDebitCached = false;
442 fChangeCached = false;
445 void BindWallet(CWallet *pwalletIn)
451 void MarkSpent(unsigned int nOut)
453 if (nOut >= vout.size())
454 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
455 vfSpent.resize(vout.size());
458 vfSpent[nOut] = true;
459 fAvailableCreditCached = false;
463 bool IsSpent(unsigned int nOut) const
465 if (nOut >= vout.size())
466 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
467 if (nOut >= vfSpent.size())
469 return (!!vfSpent[nOut]);
472 int64 GetDebit() const
478 nDebitCached = pwallet->GetDebit(*this);
483 int64 GetCredit(bool fUseCache=true) const
485 // Must wait until coinbase is safely deep enough in the chain before valuing it
486 if (IsCoinBase() && GetBlocksToMaturity() > 0)
489 // GetBalance can assume transactions in mapWallet won't change
490 if (fUseCache && fCreditCached)
491 return nCreditCached;
492 nCreditCached = pwallet->GetCredit(*this);
493 fCreditCached = true;
494 return nCreditCached;
497 int64 GetAvailableCredit(bool fUseCache=true) const
499 // Must wait until coinbase is safely deep enough in the chain before valuing it
500 if (IsCoinBase() && GetBlocksToMaturity() > 0)
503 if (fUseCache && fAvailableCreditCached)
504 return nAvailableCreditCached;
507 for (unsigned int i = 0; i < vout.size(); i++)
511 const CTxOut &txout = vout[i];
512 nCredit += pwallet->GetCredit(txout);
513 if (!MoneyRange(nCredit))
514 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
518 nAvailableCreditCached = nCredit;
519 fAvailableCreditCached = true;
524 int64 GetChange() const
527 return nChangeCached;
528 nChangeCached = pwallet->GetChange(*this);
529 fChangeCached = true;
530 return nChangeCached;
533 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
534 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
536 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
537 int64& nSent, int64& nFee) const;
539 bool IsFromMe() const
541 return (GetDebit() > 0);
544 bool IsConfirmed() const
546 // Quick answer in most cases
549 if (GetDepthInMainChain() >= 1)
551 if (!IsFromMe()) // using wtx's cached debit
554 // If no confirmations but it's from us, we can still
555 // consider it confirmed if all dependencies are confirmed
556 std::map<uint256, const CMerkleTx*> mapPrev;
557 std::vector<const CMerkleTx*> vWorkQueue;
558 vWorkQueue.reserve(vtxPrev.size()+1);
559 vWorkQueue.push_back(this);
560 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
562 const CMerkleTx* ptx = vWorkQueue[i];
566 if (ptx->GetDepthInMainChain() >= 1)
568 if (!pwallet->IsFromMe(*ptx))
573 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
574 mapPrev[tx.GetHash()] = &tx;
577 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
579 if (!mapPrev.count(txin.prevout.hash))
581 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
589 int64 GetTxTime() const;
590 int GetRequestCount() const;
592 void AddSupportingTransactions(CTxDB& txdb);
594 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
595 bool AcceptWalletTransaction();
597 void RelayWalletTransaction(CTxDB& txdb);
598 void RelayWalletTransaction();
602 /** Private key that includes an expiration date in case it never gets used. */
609 std::string strComment;
610 //// todo: add something to note what created it (user, getnewaddress, change)
611 //// maybe should have a map<string, string> property map
613 CWalletKey(int64 nExpires=0)
615 nTimeCreated = (nExpires ? GetTime() : 0);
616 nTimeExpires = nExpires;
621 if (!(nType & SER_GETHASH))
623 READWRITE(vchPrivKey);
624 READWRITE(nTimeCreated);
625 READWRITE(nTimeExpires);
626 READWRITE(strComment);
635 /** Account information.
636 * Stored in wallet with key "acc"+string account name.
641 std::vector<unsigned char> vchPubKey;
655 if (!(nType & SER_GETHASH))
657 READWRITE(vchPubKey);
663 /** Internal transfers.
664 * Database key is acentry<account><counter>.
666 class CAccountingEntry
669 std::string strAccount;
672 std::string strOtherAccount;
673 std::string strComment;
685 strOtherAccount.clear();
691 if (!(nType & SER_GETHASH))
693 // Note: strAccount is serialized as part of the key, not here.
694 READWRITE(nCreditDebit);
696 READWRITE(strOtherAccount);
697 READWRITE(strComment);
701 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);