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);
231 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
233 bool DelAddressBookName(const CBitcoinAddress& address);
235 void UpdatedTransaction(const uint256 &hashTx)
239 vWalletUpdated.push_back(hashTx);
243 void PrintWallet(const CBlock& block);
245 void Inventory(const uint256 &hash)
249 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
250 if (mi != mapRequestCount.end())
257 return setKeyPool.size();
260 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
262 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
264 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
265 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
267 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
268 bool SetMaxVersion(int nVersion);
270 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
271 int GetVersion() { return nWalletVersion; }
274 /** A key allocated from the key pool. */
280 std::vector<unsigned char> vchPubKey;
282 CReserveKey(CWallet* pwalletIn)
295 std::vector<unsigned char> GetReservedKey();
300 /** A transaction with a bunch of additional info that only the owner cares about.
301 * It includes any unrecorded transactions needed to link it back to the block chain.
303 class CWalletTx : public CMerkleTx
306 const CWallet* pwallet;
309 std::vector<CMerkleTx> vtxPrev;
310 std::map<std::string, std::string> mapValue;
311 std::vector<std::pair<std::string, std::string> > vOrderForm;
312 unsigned int fTimeReceivedIsTxTime;
313 unsigned int nTimeReceived; // time received by this node
315 std::string strFromAccount;
316 std::vector<char> vfSpent; // which outputs are already spent
319 mutable bool fDebitCached;
320 mutable bool fCreditCached;
321 mutable bool fAvailableCreditCached;
322 mutable bool fChangeCached;
323 mutable int64 nDebitCached;
324 mutable int64 nCreditCached;
325 mutable int64 nAvailableCreditCached;
326 mutable int64 nChangeCached;
333 CWalletTx(const CWallet* pwalletIn)
338 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
343 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
348 void Init(const CWallet* pwalletIn)
354 fTimeReceivedIsTxTime = false;
357 strFromAccount.clear();
359 fDebitCached = false;
360 fCreditCached = false;
361 fAvailableCreditCached = false;
362 fChangeCached = false;
365 nAvailableCreditCached = 0;
371 CWalletTx* pthis = const_cast<CWalletTx*>(this);
378 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
381 BOOST_FOREACH(char f, vfSpent)
383 str += (f ? '1' : '0');
387 pthis->mapValue["spent"] = str;
390 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
393 READWRITE(vOrderForm);
394 READWRITE(fTimeReceivedIsTxTime);
395 READWRITE(nTimeReceived);
401 pthis->strFromAccount = pthis->mapValue["fromaccount"];
403 if (mapValue.count("spent"))
404 BOOST_FOREACH(char c, pthis->mapValue["spent"])
405 pthis->vfSpent.push_back(c != '0');
407 pthis->vfSpent.assign(vout.size(), fSpent);
410 pthis->mapValue.erase("fromaccount");
411 pthis->mapValue.erase("version");
412 pthis->mapValue.erase("spent");
415 // marks certain txout's as spent
416 // returns true if any update took place
417 bool UpdateSpent(const std::vector<char>& vfNewSpent)
419 bool fReturn = false;
420 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
422 if (i == vfSpent.size())
425 if (vfNewSpent[i] && !vfSpent[i])
429 fAvailableCreditCached = false;
435 // make sure balances are recalculated
438 fCreditCached = false;
439 fAvailableCreditCached = false;
440 fDebitCached = false;
441 fChangeCached = false;
444 void BindWallet(CWallet *pwalletIn)
450 void MarkSpent(unsigned int nOut)
452 if (nOut >= vout.size())
453 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
454 vfSpent.resize(vout.size());
457 vfSpent[nOut] = true;
458 fAvailableCreditCached = false;
462 bool IsSpent(unsigned int nOut) const
464 if (nOut >= vout.size())
465 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
466 if (nOut >= vfSpent.size())
468 return (!!vfSpent[nOut]);
471 int64 GetDebit() const
477 nDebitCached = pwallet->GetDebit(*this);
482 int64 GetCredit(bool fUseCache=true) const
484 // Must wait until coinbase is safely deep enough in the chain before valuing it
485 if (IsCoinBase() && GetBlocksToMaturity() > 0)
488 // GetBalance can assume transactions in mapWallet won't change
489 if (fUseCache && fCreditCached)
490 return nCreditCached;
491 nCreditCached = pwallet->GetCredit(*this);
492 fCreditCached = true;
493 return nCreditCached;
496 int64 GetAvailableCredit(bool fUseCache=true) const
498 // Must wait until coinbase is safely deep enough in the chain before valuing it
499 if (IsCoinBase() && GetBlocksToMaturity() > 0)
502 if (fUseCache && fAvailableCreditCached)
503 return nAvailableCreditCached;
506 for (unsigned int i = 0; i < vout.size(); i++)
510 const CTxOut &txout = vout[i];
511 nCredit += pwallet->GetCredit(txout);
512 if (!MoneyRange(nCredit))
513 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
517 nAvailableCreditCached = nCredit;
518 fAvailableCreditCached = true;
523 int64 GetChange() const
526 return nChangeCached;
527 nChangeCached = pwallet->GetChange(*this);
528 fChangeCached = true;
529 return nChangeCached;
532 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
533 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
535 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
536 int64& nSent, int64& nFee) const;
538 bool IsFromMe() const
540 return (GetDebit() > 0);
543 bool IsConfirmed() const
545 // Quick answer in most cases
548 if (GetDepthInMainChain() >= 1)
550 if (!IsFromMe()) // using wtx's cached debit
553 // If no confirmations but it's from us, we can still
554 // consider it confirmed if all dependencies are confirmed
555 std::map<uint256, const CMerkleTx*> mapPrev;
556 std::vector<const CMerkleTx*> vWorkQueue;
557 vWorkQueue.reserve(vtxPrev.size()+1);
558 vWorkQueue.push_back(this);
559 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
561 const CMerkleTx* ptx = vWorkQueue[i];
565 if (ptx->GetDepthInMainChain() >= 1)
567 if (!pwallet->IsFromMe(*ptx))
572 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
573 mapPrev[tx.GetHash()] = &tx;
576 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
578 if (!mapPrev.count(txin.prevout.hash))
580 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
588 int64 GetTxTime() const;
589 int GetRequestCount() const;
591 void AddSupportingTransactions(CTxDB& txdb);
593 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
594 bool AcceptWalletTransaction();
596 void RelayWalletTransaction(CTxDB& txdb);
597 void RelayWalletTransaction();
601 /** Private key that includes an expiration date in case it never gets used. */
608 std::string strComment;
609 //// todo: add something to note what created it (user, getnewaddress, change)
610 //// maybe should have a map<string, string> property map
612 CWalletKey(int64 nExpires=0)
614 nTimeCreated = (nExpires ? GetTime() : 0);
615 nTimeExpires = nExpires;
620 if (!(nType & SER_GETHASH))
622 READWRITE(vchPrivKey);
623 READWRITE(nTimeCreated);
624 READWRITE(nTimeExpires);
625 READWRITE(strComment);
634 /** Account information.
635 * Stored in wallet with key "acc"+string account name.
640 std::vector<unsigned char> vchPubKey;
654 if (!(nType & SER_GETHASH))
656 READWRITE(vchPubKey);
662 /** Internal transfers.
663 * Database key is acentry<account><counter>.
665 class CAccountingEntry
668 std::string strAccount;
671 std::string strOtherAccount;
672 std::string strComment;
684 strOtherAccount.clear();
690 if (!(nType & SER_GETHASH))
692 // Note: strAccount is serialized as part of the key, not here.
693 READWRITE(nCreditDebit);
695 READWRITE(strOtherAccount);
696 READWRITE(strComment);
700 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);