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
13 extern bool fWalletUnlockStakeOnly;
19 // A CWallet is an extension of a keystore, which also maintains a set of
20 // transactions and balances, and provides the ability to create new
22 class CWallet : public CCryptoKeyStore
25 bool SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
26 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
28 CWalletDB *pwalletdbEncryption;
31 mutable CCriticalSection cs_wallet;
34 std::string strWalletFile;
36 std::set<int64> setKeyPool;
38 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
39 MasterKeyMap mapMasterKeys;
40 unsigned int nMasterKeyMaxID;
46 pwalletdbEncryption = NULL;
48 CWallet(std::string strWalletFileIn)
50 strWalletFile = strWalletFileIn;
53 pwalletdbEncryption = NULL;
56 std::map<uint256, CWalletTx> mapWallet;
57 std::vector<uint256> vWalletUpdated;
59 std::map<uint256, int> mapRequestCount;
61 std::map<CBitcoinAddress, std::string> mapAddressBook;
63 std::vector<unsigned char> vchDefaultKey;
65 // keystore implementation
66 // Adds a key to the store, and saves it to disk.
67 bool AddKey(const CKey& key);
68 // Adds a key to the store, without saving it to disk (used by LoadWallet)
69 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
71 // Adds an encrypted key to the store, and saves it to disk.
72 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
73 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
74 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
76 bool Unlock(const SecureString& strWalletPassphrase);
77 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
78 bool EncryptWallet(const SecureString& strWalletPassphrase);
80 bool AddToWallet(const CWalletTx& wtxIn);
81 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
82 bool EraseFromWallet(uint256 hash);
83 void WalletUpdateSpent(const CTransaction& prevout);
84 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
85 void ReacceptWalletTransactions();
86 void ResendWalletTransactions();
87 int64 GetBalance() const;
88 int64 GetUnconfirmedBalance() const;
89 int64 GetStake() const;
90 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
91 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
92 bool CreateCoinStake(CScript scriptPubKey, CTransaction& txNew);
93 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
94 bool BroadcastTransaction(CWalletTx& wtxNew);
95 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
96 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
100 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
101 void KeepKey(int64 nIndex);
102 void ReturnKey(int64 nIndex);
103 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
104 int64 GetOldestKeyPoolTime();
106 bool IsMine(const CTxIn& txin) const;
107 int64 GetDebit(const CTxIn& txin) const;
108 bool IsMine(const CTxOut& txout) const
110 return ::IsMine(*this, txout.scriptPubKey);
112 int64 GetCredit(const CTxOut& txout) const
114 if (!MoneyRange(txout.nValue))
115 throw std::runtime_error("CWallet::GetCredit() : value out of range");
116 return (IsMine(txout) ? txout.nValue : 0);
118 bool IsChange(const CTxOut& txout) const
120 CBitcoinAddress address;
121 if (ExtractAddress(txout.scriptPubKey, this, address))
122 CRITICAL_BLOCK(cs_wallet)
123 if (!mapAddressBook.count(address))
127 int64 GetChange(const CTxOut& txout) const
129 if (!MoneyRange(txout.nValue))
130 throw std::runtime_error("CWallet::GetChange() : value out of range");
131 return (IsChange(txout) ? txout.nValue : 0);
133 bool IsMine(const CTransaction& tx) const
135 BOOST_FOREACH(const CTxOut& txout, tx.vout)
140 bool IsFromMe(const CTransaction& tx) const
142 return (GetDebit(tx) > 0);
144 int64 GetDebit(const CTransaction& tx) const
147 BOOST_FOREACH(const CTxIn& txin, tx.vin)
149 nDebit += GetDebit(txin);
150 if (!MoneyRange(nDebit))
151 throw std::runtime_error("CWallet::GetDebit() : value out of range");
155 int64 GetCredit(const CTransaction& tx) const
158 BOOST_FOREACH(const CTxOut& txout, tx.vout)
160 nCredit += GetCredit(txout);
161 if (!MoneyRange(nCredit))
162 throw std::runtime_error("CWallet::GetCredit() : value out of range");
166 int64 GetChange(const CTransaction& tx) const
169 BOOST_FOREACH(const CTxOut& txout, tx.vout)
171 nChange += GetChange(txout);
172 if (!MoneyRange(nChange))
173 throw std::runtime_error("CWallet::GetChange() : value out of range");
177 void SetBestChain(const CBlockLocator& loc)
179 CWalletDB walletdb(strWalletFile);
180 walletdb.WriteBestBlock(loc);
183 int LoadWallet(bool& fFirstRunRet);
184 // bool BackupWallet(const std::string& strDest);
186 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
188 bool DelAddressBookName(const CBitcoinAddress& address);
190 void UpdatedTransaction(const uint256 &hashTx)
192 CRITICAL_BLOCK(cs_wallet)
193 vWalletUpdated.push_back(hashTx);
196 void PrintWallet(const CBlock& block);
198 void Inventory(const uint256 &hash)
200 CRITICAL_BLOCK(cs_wallet)
202 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
203 if (mi != mapRequestCount.end())
210 return setKeyPool.size();
213 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
215 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
217 bool CheckSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion);
226 std::vector<unsigned char> vchPubKey;
228 CReserveKey(CWallet* pwalletIn)
241 std::vector<unsigned char> GetReservedKey();
247 // A transaction with a bunch of additional info that only the owner cares
248 // about. It includes any unrecorded transactions needed to link it back
249 // to the block chain.
251 class CWalletTx : public CMerkleTx
254 const CWallet* pwallet;
256 std::vector<CMerkleTx> vtxPrev;
257 std::map<std::string, std::string> mapValue;
258 std::vector<std::pair<std::string, std::string> > vOrderForm;
259 unsigned int fTimeReceivedIsTxTime;
260 unsigned int nTimeReceived; // time received by this node
262 std::string strFromAccount;
263 std::vector<char> vfSpent; // which outputs are already spent
266 mutable char fDebitCached;
267 mutable char fCreditCached;
268 mutable char fAvailableCreditCached;
269 mutable char fChangeCached;
270 mutable int64 nDebitCached;
271 mutable int64 nCreditCached;
272 mutable int64 nAvailableCreditCached;
273 mutable int64 nChangeCached;
275 // memory only UI hints
276 mutable unsigned int nTimeDisplayed;
277 mutable int nLinesDisplayed;
278 mutable char fConfirmedDisplayed;
285 CWalletTx(const CWallet* pwalletIn)
290 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
295 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
300 void Init(const CWallet* pwalletIn)
306 fTimeReceivedIsTxTime = false;
309 strFromAccount.clear();
311 fDebitCached = false;
312 fCreditCached = false;
313 fAvailableCreditCached = false;
314 fChangeCached = false;
317 nAvailableCreditCached = 0;
321 fConfirmedDisplayed = false;
326 CWalletTx* pthis = const_cast<CWalletTx*>(this);
333 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
336 BOOST_FOREACH(char f, vfSpent)
338 str += (f ? '1' : '0');
342 pthis->mapValue["spent"] = str;
345 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
348 READWRITE(vOrderForm);
349 READWRITE(fTimeReceivedIsTxTime);
350 READWRITE(nTimeReceived);
356 pthis->strFromAccount = pthis->mapValue["fromaccount"];
358 if (mapValue.count("spent"))
359 BOOST_FOREACH(char c, pthis->mapValue["spent"])
360 pthis->vfSpent.push_back(c != '0');
362 pthis->vfSpent.assign(vout.size(), fSpent);
365 pthis->mapValue.erase("fromaccount");
366 pthis->mapValue.erase("version");
367 pthis->mapValue.erase("spent");
370 // marks certain txout's as spent
371 // returns true if any update took place
372 bool UpdateSpent(const std::vector<char>& vfNewSpent)
374 bool fReturn = false;
375 for (int i=0; i < vfNewSpent.size(); i++)
377 if (i == vfSpent.size())
380 if (vfNewSpent[i] && !vfSpent[i])
384 fAvailableCreditCached = false;
390 // make sure balances are recalculated
393 fCreditCached = false;
394 fAvailableCreditCached = false;
395 fDebitCached = false;
396 fChangeCached = false;
399 void MarkSpent(unsigned int nOut)
401 if (nOut >= vout.size())
402 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
403 vfSpent.resize(vout.size());
406 vfSpent[nOut] = true;
407 fAvailableCreditCached = false;
411 bool IsSpent(unsigned int nOut) const
413 if (nOut >= vout.size())
414 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
415 if (nOut >= vfSpent.size())
417 return (!!vfSpent[nOut]);
420 int64 GetDebit() const
426 nDebitCached = pwallet->GetDebit(*this);
431 int64 GetCredit(bool fUseCache=true) const
433 // Must wait until coinbase is safely deep enough in the chain before valuing it
434 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
437 // GetBalance can assume transactions in mapWallet won't change
438 if (fUseCache && fCreditCached)
439 return nCreditCached;
440 nCreditCached = pwallet->GetCredit(*this);
441 fCreditCached = true;
442 return nCreditCached;
445 int64 GetAvailableCredit(bool fUseCache=true) const
447 // Must wait until coinbase is safely deep enough in the chain before valuing it
448 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
451 if (fUseCache && fAvailableCreditCached)
452 return nAvailableCreditCached;
455 for (int i = 0; i < vout.size(); i++)
459 const CTxOut &txout = vout[i];
460 nCredit += pwallet->GetCredit(txout);
461 if (!MoneyRange(nCredit))
462 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
466 nAvailableCreditCached = nCredit;
467 fAvailableCreditCached = true;
472 int64 GetChange() const
475 return nChangeCached;
476 nChangeCached = pwallet->GetChange(*this);
477 fChangeCached = true;
478 return nChangeCached;
481 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
482 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
484 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
485 int64& nSent, int64& nFee) const;
487 bool IsFromMe() const
489 return (GetDebit() > 0);
492 bool IsConfirmed() const
494 // Quick answer in most cases
497 if (GetDepthInMainChain() >= 1)
499 if (!IsFromMe()) // using wtx's cached debit
502 // If no confirmations but it's from us, we can still
503 // consider it confirmed if all dependencies are confirmed
504 std::map<uint256, const CMerkleTx*> mapPrev;
505 std::vector<const CMerkleTx*> vWorkQueue;
506 vWorkQueue.reserve(vtxPrev.size()+1);
507 vWorkQueue.push_back(this);
508 for (int i = 0; i < vWorkQueue.size(); i++)
510 const CMerkleTx* ptx = vWorkQueue[i];
514 if (ptx->GetDepthInMainChain() >= 1)
516 if (!pwallet->IsFromMe(*ptx))
520 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
521 mapPrev[tx.GetHash()] = &tx;
523 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
525 if (!mapPrev.count(txin.prevout.hash))
527 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
535 int64 GetTxTime() const;
536 int GetRequestCount() const;
538 void AddSupportingTransactions(CTxDB& txdb);
540 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
541 bool AcceptWalletTransaction();
543 void RelayWalletTransaction(CTxDB& txdb);
544 void RelayWalletTransaction();
549 // Private key that includes an expiration date in case it never gets used.
557 std::string strComment;
558 //// todo: add something to note what created it (user, getnewaddress, change)
559 //// maybe should have a map<string, string> property map
561 CWalletKey(int64 nExpires=0)
563 nTimeCreated = (nExpires ? GetTime() : 0);
564 nTimeExpires = nExpires;
569 if (!(nType & SER_GETHASH))
571 READWRITE(vchPrivKey);
572 READWRITE(nTimeCreated);
573 READWRITE(nTimeExpires);
574 READWRITE(strComment);
584 // Account information.
585 // Stored in wallet with key "acc"+string account name
590 std::vector<unsigned char> vchPubKey;
604 if (!(nType & SER_GETHASH))
606 READWRITE(vchPubKey);
613 // Internal transfers.
614 // Database key is acentry<account><counter>
616 class CAccountingEntry
619 std::string strAccount;
622 std::string strOtherAccount;
623 std::string strComment;
635 strOtherAccount.clear();
641 if (!(nType & SER_GETHASH))
643 // Note: strAccount is serialized as part of the key, not here.
644 READWRITE(nCreditDebit);
646 READWRITE(strOtherAccount);
647 READWRITE(strComment);
651 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);