1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_WALLET_H
7 #define BITCOIN_WALLET_H
17 // A CWallet is an extension of a keystore, which also maintains a set of
18 // transactions and balances, and provides the ability to create new
20 class CWallet : public CCryptoKeyStore
23 bool SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
24 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
26 CWalletDB *pwalletdbEncryption;
29 mutable CCriticalSection cs_wallet;
32 std::string strWalletFile;
34 std::set<int64> setKeyPool;
36 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
37 MasterKeyMap mapMasterKeys;
38 unsigned int nMasterKeyMaxID;
44 pwalletdbEncryption = NULL;
46 CWallet(std::string strWalletFileIn)
48 strWalletFile = strWalletFileIn;
51 pwalletdbEncryption = NULL;
54 std::map<uint256, CWalletTx> mapWallet;
55 std::vector<uint256> vWalletUpdated;
57 std::map<uint256, int> mapRequestCount;
59 std::map<CBitcoinAddress, std::string> mapAddressBook;
61 std::vector<unsigned char> vchDefaultKey;
63 // keystore implementation
64 // Adds a key to the store, and saves it to disk.
65 bool AddKey(const CKey& key);
66 // Adds a key to the store, without saving it to disk (used by LoadWallet)
67 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
69 // Adds an encrypted key to the store, and saves it to disk.
70 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
71 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
72 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
74 bool Unlock(const SecureString& strWalletPassphrase);
75 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
76 bool EncryptWallet(const SecureString& strWalletPassphrase);
78 bool AddToWallet(const CWalletTx& wtxIn);
79 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
80 bool EraseFromWallet(uint256 hash);
81 void WalletUpdateSpent(const CTransaction& prevout);
82 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
83 void ReacceptWalletTransactions();
84 void ResendWalletTransactions();
85 int64 GetBalance() const;
86 int64 GetUnconfirmedBalance() const;
87 int64 GetStake() const;
88 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
89 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
90 bool CreateCoinStake(CScript scriptPubKey, CTransaction& txNew);
91 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
92 bool BroadcastTransaction(CWalletTx& wtxNew);
93 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
94 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
98 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
99 void KeepKey(int64 nIndex);
100 void ReturnKey(int64 nIndex);
101 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
102 int64 GetOldestKeyPoolTime();
104 bool IsMine(const CTxIn& txin) const;
105 int64 GetDebit(const CTxIn& txin) const;
106 bool IsMine(const CTxOut& txout) const
108 return ::IsMine(*this, txout.scriptPubKey);
110 int64 GetCredit(const CTxOut& txout) const
112 if (!MoneyRange(txout.nValue))
113 throw std::runtime_error("CWallet::GetCredit() : value out of range");
114 return (IsMine(txout) ? txout.nValue : 0);
116 bool IsChange(const CTxOut& txout) const
118 CBitcoinAddress address;
119 if (ExtractAddress(txout.scriptPubKey, this, address))
120 CRITICAL_BLOCK(cs_wallet)
121 if (!mapAddressBook.count(address))
125 int64 GetChange(const CTxOut& txout) const
127 if (!MoneyRange(txout.nValue))
128 throw std::runtime_error("CWallet::GetChange() : value out of range");
129 return (IsChange(txout) ? txout.nValue : 0);
131 bool IsMine(const CTransaction& tx) const
133 BOOST_FOREACH(const CTxOut& txout, tx.vout)
138 bool IsFromMe(const CTransaction& tx) const
140 return (GetDebit(tx) > 0);
142 int64 GetDebit(const CTransaction& tx) const
145 BOOST_FOREACH(const CTxIn& txin, tx.vin)
147 nDebit += GetDebit(txin);
148 if (!MoneyRange(nDebit))
149 throw std::runtime_error("CWallet::GetDebit() : value out of range");
153 int64 GetCredit(const CTransaction& tx) const
156 BOOST_FOREACH(const CTxOut& txout, tx.vout)
158 nCredit += GetCredit(txout);
159 if (!MoneyRange(nCredit))
160 throw std::runtime_error("CWallet::GetCredit() : value out of range");
164 int64 GetChange(const CTransaction& tx) const
167 BOOST_FOREACH(const CTxOut& txout, tx.vout)
169 nChange += GetChange(txout);
170 if (!MoneyRange(nChange))
171 throw std::runtime_error("CWallet::GetChange() : value out of range");
175 void SetBestChain(const CBlockLocator& loc)
177 CWalletDB walletdb(strWalletFile);
178 walletdb.WriteBestBlock(loc);
181 int LoadWallet(bool& fFirstRunRet);
182 // bool BackupWallet(const std::string& strDest);
184 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
186 bool DelAddressBookName(const CBitcoinAddress& address);
188 void UpdatedTransaction(const uint256 &hashTx)
190 CRITICAL_BLOCK(cs_wallet)
191 vWalletUpdated.push_back(hashTx);
194 void PrintWallet(const CBlock& block);
196 void Inventory(const uint256 &hash)
198 CRITICAL_BLOCK(cs_wallet)
200 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
201 if (mi != mapRequestCount.end())
208 return setKeyPool.size();
211 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
213 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
222 std::vector<unsigned char> vchPubKey;
224 CReserveKey(CWallet* pwalletIn)
237 std::vector<unsigned char> GetReservedKey();
243 // A transaction with a bunch of additional info that only the owner cares
244 // about. It includes any unrecorded transactions needed to link it back
245 // to the block chain.
247 class CWalletTx : public CMerkleTx
250 const CWallet* pwallet;
252 std::vector<CMerkleTx> vtxPrev;
253 std::map<std::string, std::string> mapValue;
254 std::vector<std::pair<std::string, std::string> > vOrderForm;
255 unsigned int fTimeReceivedIsTxTime;
256 unsigned int nTimeReceived; // time received by this node
258 std::string strFromAccount;
259 std::vector<char> vfSpent; // which outputs are already spent
262 mutable char fDebitCached;
263 mutable char fCreditCached;
264 mutable char fAvailableCreditCached;
265 mutable char fChangeCached;
266 mutable int64 nDebitCached;
267 mutable int64 nCreditCached;
268 mutable int64 nAvailableCreditCached;
269 mutable int64 nChangeCached;
271 // memory only UI hints
272 mutable unsigned int nTimeDisplayed;
273 mutable int nLinesDisplayed;
274 mutable char fConfirmedDisplayed;
281 CWalletTx(const CWallet* pwalletIn)
286 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
291 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
296 void Init(const CWallet* pwalletIn)
302 fTimeReceivedIsTxTime = false;
305 strFromAccount.clear();
307 fDebitCached = false;
308 fCreditCached = false;
309 fAvailableCreditCached = false;
310 fChangeCached = false;
313 nAvailableCreditCached = 0;
317 fConfirmedDisplayed = false;
322 CWalletTx* pthis = const_cast<CWalletTx*>(this);
329 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
332 BOOST_FOREACH(char f, vfSpent)
334 str += (f ? '1' : '0');
338 pthis->mapValue["spent"] = str;
341 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
344 READWRITE(vOrderForm);
345 READWRITE(fTimeReceivedIsTxTime);
346 READWRITE(nTimeReceived);
352 pthis->strFromAccount = pthis->mapValue["fromaccount"];
354 if (mapValue.count("spent"))
355 BOOST_FOREACH(char c, pthis->mapValue["spent"])
356 pthis->vfSpent.push_back(c != '0');
358 pthis->vfSpent.assign(vout.size(), fSpent);
361 pthis->mapValue.erase("fromaccount");
362 pthis->mapValue.erase("version");
363 pthis->mapValue.erase("spent");
366 // marks certain txout's as spent
367 // returns true if any update took place
368 bool UpdateSpent(const std::vector<char>& vfNewSpent)
370 bool fReturn = false;
371 for (int i=0; i < vfNewSpent.size(); i++)
373 if (i == vfSpent.size())
376 if (vfNewSpent[i] && !vfSpent[i])
380 fAvailableCreditCached = false;
386 // make sure balances are recalculated
389 fCreditCached = false;
390 fAvailableCreditCached = false;
391 fDebitCached = false;
392 fChangeCached = false;
395 void MarkSpent(unsigned int nOut)
397 if (nOut >= vout.size())
398 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
399 vfSpent.resize(vout.size());
402 vfSpent[nOut] = true;
403 fAvailableCreditCached = false;
407 bool IsSpent(unsigned int nOut) const
409 if (nOut >= vout.size())
410 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
411 if (nOut >= vfSpent.size())
413 return (!!vfSpent[nOut]);
416 int64 GetDebit() const
422 nDebitCached = pwallet->GetDebit(*this);
427 int64 GetCredit(bool fUseCache=true) const
429 // Must wait until coinbase is safely deep enough in the chain before valuing it
430 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
433 // GetBalance can assume transactions in mapWallet won't change
434 if (fUseCache && fCreditCached)
435 return nCreditCached;
436 nCreditCached = pwallet->GetCredit(*this);
437 fCreditCached = true;
438 return nCreditCached;
441 int64 GetAvailableCredit(bool fUseCache=true) const
443 // Must wait until coinbase is safely deep enough in the chain before valuing it
444 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
447 if (fUseCache && fAvailableCreditCached)
448 return nAvailableCreditCached;
451 for (int i = 0; i < vout.size(); i++)
455 const CTxOut &txout = vout[i];
456 nCredit += pwallet->GetCredit(txout);
457 if (!MoneyRange(nCredit))
458 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
462 nAvailableCreditCached = nCredit;
463 fAvailableCreditCached = true;
468 int64 GetChange() const
471 return nChangeCached;
472 nChangeCached = pwallet->GetChange(*this);
473 fChangeCached = true;
474 return nChangeCached;
477 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
478 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
480 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
481 int64& nSent, int64& nFee) const;
483 bool IsFromMe() const
485 return (GetDebit() > 0);
488 bool IsConfirmed() const
490 // Quick answer in most cases
493 if (GetDepthInMainChain() >= 1)
495 if (!IsFromMe()) // using wtx's cached debit
498 // If no confirmations but it's from us, we can still
499 // consider it confirmed if all dependencies are confirmed
500 std::map<uint256, const CMerkleTx*> mapPrev;
501 std::vector<const CMerkleTx*> vWorkQueue;
502 vWorkQueue.reserve(vtxPrev.size()+1);
503 vWorkQueue.push_back(this);
504 for (int i = 0; i < vWorkQueue.size(); i++)
506 const CMerkleTx* ptx = vWorkQueue[i];
510 if (ptx->GetDepthInMainChain() >= 1)
512 if (!pwallet->IsFromMe(*ptx))
516 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
517 mapPrev[tx.GetHash()] = &tx;
519 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
521 if (!mapPrev.count(txin.prevout.hash))
523 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
531 int64 GetTxTime() const;
532 int GetRequestCount() const;
534 void AddSupportingTransactions(CTxDB& txdb);
536 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
537 bool AcceptWalletTransaction();
539 void RelayWalletTransaction(CTxDB& txdb);
540 void RelayWalletTransaction();
545 // Private key that includes an expiration date in case it never gets used.
553 std::string strComment;
554 //// todo: add something to note what created it (user, getnewaddress, change)
555 //// maybe should have a map<string, string> property map
557 CWalletKey(int64 nExpires=0)
559 nTimeCreated = (nExpires ? GetTime() : 0);
560 nTimeExpires = nExpires;
565 if (!(nType & SER_GETHASH))
567 READWRITE(vchPrivKey);
568 READWRITE(nTimeCreated);
569 READWRITE(nTimeExpires);
570 READWRITE(strComment);
580 // Account information.
581 // Stored in wallet with key "acc"+string account name
586 std::vector<unsigned char> vchPubKey;
600 if (!(nType & SER_GETHASH))
602 READWRITE(vchPubKey);
609 // Internal transfers.
610 // Database key is acentry<account><counter>
612 class CAccountingEntry
615 std::string strAccount;
618 std::string strOtherAccount;
619 std::string strComment;
631 strOtherAccount.clear();
637 if (!(nType & SER_GETHASH))
639 // Note: strAccount is serialized as part of the key, not here.
640 READWRITE(nCreditDebit);
642 READWRITE(strOtherAccount);
643 READWRITE(strComment);
647 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);