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
19 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
21 FEATURE_WALLETCRYPT = 40000, // wallet encryption
22 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
24 FEATURE_LATEST = 60000
27 // A CWallet is an extension of a keystore, which also maintains a set of
28 // transactions and balances, and provides the ability to create new
30 class CWallet : public CCryptoKeyStore
33 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
34 bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
36 CWalletDB *pwalletdbEncryption;
38 // the current wallet version: clients below this version are not able to load the wallet
41 // the maxmimum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
42 int nWalletMaxVersion;
45 mutable CCriticalSection cs_wallet;
48 std::string strWalletFile;
50 std::set<int64> setKeyPool;
53 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
54 MasterKeyMap mapMasterKeys;
55 unsigned int nMasterKeyMaxID;
59 nWalletVersion = FEATURE_BASE;
60 nWalletMaxVersion = FEATURE_BASE;
63 pwalletdbEncryption = NULL;
65 CWallet(std::string strWalletFileIn)
67 nWalletVersion = FEATURE_BASE;
68 nWalletMaxVersion = FEATURE_BASE;
69 strWalletFile = strWalletFileIn;
72 pwalletdbEncryption = NULL;
75 std::map<uint256, CWalletTx> mapWallet;
76 std::vector<uint256> vWalletUpdated;
78 std::map<uint256, int> mapRequestCount;
80 std::map<CBitcoinAddress, std::string> mapAddressBook;
82 std::vector<unsigned char> vchDefaultKey;
84 // check whether we are allowed to upgrade (or already support) to the named feature
85 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
87 // keystore implementation
89 std::vector<unsigned char> GenerateNewKey();
90 // Adds a key to the store, and saves it to disk.
91 bool AddKey(const CKey& key);
92 // Adds a key to the store, without saving it to disk (used by LoadWallet)
93 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
95 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
97 // Adds an encrypted key to the store, and saves it to disk.
98 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
99 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
100 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
101 bool AddCScript(const CScript& redeemScript);
102 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
104 bool Unlock(const SecureString& strWalletPassphrase);
105 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
106 bool EncryptWallet(const SecureString& strWalletPassphrase);
109 bool AddToWallet(const CWalletTx& wtxIn);
110 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
111 bool EraseFromWallet(uint256 hash);
112 void WalletUpdateSpent(const CTransaction& prevout);
113 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
114 int ScanForWalletTransaction(const uint256& hashTx);
115 void ReacceptWalletTransactions();
116 void ResendWalletTransactions();
117 int64 GetBalance() const;
118 int64 GetUnconfirmedBalance() const;
119 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
120 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
121 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
122 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
123 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
127 int64 AddReserveKey(const CKeyPool& keypool);
128 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
129 void KeepKey(int64 nIndex);
130 void ReturnKey(int64 nIndex);
131 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
132 int64 GetOldestKeyPoolTime();
133 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
135 bool IsMine(const CTxIn& txin) const;
136 int64 GetDebit(const CTxIn& txin) const;
137 bool IsMine(const CTxOut& txout) const
139 return ::IsMine(*this, txout.scriptPubKey);
141 int64 GetCredit(const CTxOut& txout) const
143 if (!MoneyRange(txout.nValue))
144 throw std::runtime_error("CWallet::GetCredit() : value out of range");
145 return (IsMine(txout) ? txout.nValue : 0);
147 bool IsChange(const CTxOut& txout) const;
148 int64 GetChange(const CTxOut& txout) const
150 if (!MoneyRange(txout.nValue))
151 throw std::runtime_error("CWallet::GetChange() : value out of range");
152 return (IsChange(txout) ? txout.nValue : 0);
154 bool IsMine(const CTransaction& tx) const
156 BOOST_FOREACH(const CTxOut& txout, tx.vout)
161 bool IsFromMe(const CTransaction& tx) const
163 return (GetDebit(tx) > 0);
165 int64 GetDebit(const CTransaction& tx) const
168 BOOST_FOREACH(const CTxIn& txin, tx.vin)
170 nDebit += GetDebit(txin);
171 if (!MoneyRange(nDebit))
172 throw std::runtime_error("CWallet::GetDebit() : value out of range");
176 int64 GetCredit(const CTransaction& tx) const
179 BOOST_FOREACH(const CTxOut& txout, tx.vout)
181 nCredit += GetCredit(txout);
182 if (!MoneyRange(nCredit))
183 throw std::runtime_error("CWallet::GetCredit() : value out of range");
187 int64 GetChange(const CTransaction& tx) const
190 BOOST_FOREACH(const CTxOut& txout, tx.vout)
192 nChange += GetChange(txout);
193 if (!MoneyRange(nChange))
194 throw std::runtime_error("CWallet::GetChange() : value out of range");
198 void SetBestChain(const CBlockLocator& loc)
200 CWalletDB walletdb(strWalletFile);
201 walletdb.WriteBestBlock(loc);
204 int LoadWallet(bool& fFirstRunRet);
205 // bool BackupWallet(const std::string& strDest);
207 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
209 bool DelAddressBookName(const CBitcoinAddress& address);
211 void UpdatedTransaction(const uint256 &hashTx)
213 CRITICAL_BLOCK(cs_wallet)
214 vWalletUpdated.push_back(hashTx);
217 void PrintWallet(const CBlock& block);
219 void Inventory(const uint256 &hash)
221 CRITICAL_BLOCK(cs_wallet)
223 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
224 if (mi != mapRequestCount.end())
231 return setKeyPool.size();
234 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
236 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
238 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
239 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
241 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
242 bool SetMaxVersion(int nVersion);
244 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
245 int GetVersion() { return nWalletVersion; }
254 std::vector<unsigned char> vchPubKey;
256 CReserveKey(CWallet* pwalletIn)
269 std::vector<unsigned char> GetReservedKey();
275 // A transaction with a bunch of additional info that only the owner cares
276 // about. It includes any unrecorded transactions needed to link it back
277 // to the block chain.
279 class CWalletTx : public CMerkleTx
282 const CWallet* pwallet;
285 std::vector<CMerkleTx> vtxPrev;
286 std::map<std::string, std::string> mapValue;
287 std::vector<std::pair<std::string, std::string> > vOrderForm;
288 unsigned int fTimeReceivedIsTxTime;
289 unsigned int nTimeReceived; // time received by this node
291 std::string strFromAccount;
292 std::vector<char> vfSpent; // which outputs are already spent
295 mutable char fDebitCached;
296 mutable char fCreditCached;
297 mutable char fAvailableCreditCached;
298 mutable char fChangeCached;
299 mutable int64 nDebitCached;
300 mutable int64 nCreditCached;
301 mutable int64 nAvailableCreditCached;
302 mutable int64 nChangeCached;
304 // memory only UI hints
305 mutable unsigned int nTimeDisplayed;
306 mutable int nLinesDisplayed;
307 mutable char fConfirmedDisplayed;
314 CWalletTx(const CWallet* pwalletIn)
319 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
324 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
329 void Init(const CWallet* pwalletIn)
335 fTimeReceivedIsTxTime = false;
338 strFromAccount.clear();
340 fDebitCached = false;
341 fCreditCached = false;
342 fAvailableCreditCached = false;
343 fChangeCached = false;
346 nAvailableCreditCached = 0;
350 fConfirmedDisplayed = false;
355 CWalletTx* pthis = const_cast<CWalletTx*>(this);
362 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
365 BOOST_FOREACH(char f, vfSpent)
367 str += (f ? '1' : '0');
371 pthis->mapValue["spent"] = str;
374 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
377 READWRITE(vOrderForm);
378 READWRITE(fTimeReceivedIsTxTime);
379 READWRITE(nTimeReceived);
385 pthis->strFromAccount = pthis->mapValue["fromaccount"];
387 if (mapValue.count("spent"))
388 BOOST_FOREACH(char c, pthis->mapValue["spent"])
389 pthis->vfSpent.push_back(c != '0');
391 pthis->vfSpent.assign(vout.size(), fSpent);
394 pthis->mapValue.erase("fromaccount");
395 pthis->mapValue.erase("version");
396 pthis->mapValue.erase("spent");
399 // marks certain txout's as spent
400 // returns true if any update took place
401 bool UpdateSpent(const std::vector<char>& vfNewSpent)
403 bool fReturn = false;
404 for (int i=0; i < vfNewSpent.size(); i++)
406 if (i == vfSpent.size())
409 if (vfNewSpent[i] && !vfSpent[i])
413 fAvailableCreditCached = false;
419 // make sure balances are recalculated
422 fCreditCached = false;
423 fAvailableCreditCached = false;
424 fDebitCached = false;
425 fChangeCached = false;
428 void BindWallet(CWallet *pwalletIn)
434 void MarkSpent(unsigned int nOut)
436 if (nOut >= vout.size())
437 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
438 vfSpent.resize(vout.size());
441 vfSpent[nOut] = true;
442 fAvailableCreditCached = false;
446 bool IsSpent(unsigned int nOut) const
448 if (nOut >= vout.size())
449 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
450 if (nOut >= vfSpent.size())
452 return (!!vfSpent[nOut]);
455 int64 GetDebit() const
461 nDebitCached = pwallet->GetDebit(*this);
466 int64 GetCredit(bool fUseCache=true) const
468 // Must wait until coinbase is safely deep enough in the chain before valuing it
469 if (IsCoinBase() && GetBlocksToMaturity() > 0)
472 // GetBalance can assume transactions in mapWallet won't change
473 if (fUseCache && fCreditCached)
474 return nCreditCached;
475 nCreditCached = pwallet->GetCredit(*this);
476 fCreditCached = true;
477 return nCreditCached;
480 int64 GetAvailableCredit(bool fUseCache=true) const
482 // Must wait until coinbase is safely deep enough in the chain before valuing it
483 if (IsCoinBase() && GetBlocksToMaturity() > 0)
486 if (fUseCache && fAvailableCreditCached)
487 return nAvailableCreditCached;
490 for (int i = 0; i < vout.size(); i++)
494 const CTxOut &txout = vout[i];
495 nCredit += pwallet->GetCredit(txout);
496 if (!MoneyRange(nCredit))
497 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
501 nAvailableCreditCached = nCredit;
502 fAvailableCreditCached = true;
507 int64 GetChange() const
510 return nChangeCached;
511 nChangeCached = pwallet->GetChange(*this);
512 fChangeCached = true;
513 return nChangeCached;
516 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
517 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
519 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
520 int64& nSent, int64& nFee) const;
522 bool IsFromMe() const
524 return (GetDebit() > 0);
527 bool IsConfirmed() const
529 // Quick answer in most cases
532 if (GetDepthInMainChain() >= 1)
534 if (!IsFromMe()) // using wtx's cached debit
537 // If no confirmations but it's from us, we can still
538 // consider it confirmed if all dependencies are confirmed
539 std::map<uint256, const CMerkleTx*> mapPrev;
540 std::vector<const CMerkleTx*> vWorkQueue;
541 vWorkQueue.reserve(vtxPrev.size()+1);
542 vWorkQueue.push_back(this);
543 for (int i = 0; i < vWorkQueue.size(); i++)
545 const CMerkleTx* ptx = vWorkQueue[i];
549 if (ptx->GetDepthInMainChain() >= 1)
551 if (!pwallet->IsFromMe(*ptx))
555 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
556 mapPrev[tx.GetHash()] = &tx;
558 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
560 if (!mapPrev.count(txin.prevout.hash))
562 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
570 int64 GetTxTime() const;
571 int GetRequestCount() const;
573 void AddSupportingTransactions(CTxDB& txdb);
575 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
576 bool AcceptWalletTransaction();
578 void RelayWalletTransaction(CTxDB& txdb);
579 void RelayWalletTransaction();
584 // Private key that includes an expiration date in case it never gets used.
592 std::string strComment;
593 //// todo: add something to note what created it (user, getnewaddress, change)
594 //// maybe should have a map<string, string> property map
596 CWalletKey(int64 nExpires=0)
598 nTimeCreated = (nExpires ? GetTime() : 0);
599 nTimeExpires = nExpires;
604 if (!(nType & SER_GETHASH))
606 READWRITE(vchPrivKey);
607 READWRITE(nTimeCreated);
608 READWRITE(nTimeExpires);
609 READWRITE(strComment);
619 // Account information.
620 // Stored in wallet with key "acc"+string account name
625 std::vector<unsigned char> vchPubKey;
639 if (!(nType & SER_GETHASH))
641 READWRITE(vchPubKey);
648 // Internal transfers.
649 // Database key is acentry<account><counter>
651 class CAccountingEntry
654 std::string strAccount;
657 std::string strOtherAccount;
658 std::string strComment;
670 strOtherAccount.clear();
676 if (!(nType & SER_GETHASH))
678 // Note: strAccount is serialized as part of the key, not here.
679 READWRITE(nCreditDebit);
681 READWRITE(strOtherAccount);
682 READWRITE(strComment);
686 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);