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 int64 GetNewMint() const;
91 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
92 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
93 bool CreateCoinStake(unsigned int nBits, CTransaction& txNew);
94 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
95 bool BroadcastTransaction(CWalletTx& wtxNew);
96 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
97 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
101 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
102 void KeepKey(int64 nIndex);
103 void ReturnKey(int64 nIndex);
104 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
105 int64 GetOldestKeyPoolTime();
107 bool IsMine(const CTxIn& txin) const;
108 int64 GetDebit(const CTxIn& txin) const;
109 bool IsMine(const CTxOut& txout) const
111 return ::IsMine(*this, txout.scriptPubKey);
113 int64 GetCredit(const CTxOut& txout) const
115 if (!MoneyRange(txout.nValue))
116 throw std::runtime_error("CWallet::GetCredit() : value out of range");
117 return (IsMine(txout) ? txout.nValue : 0);
119 bool IsChange(const CTxOut& txout) const
121 CBitcoinAddress address;
122 if (ExtractAddress(txout.scriptPubKey, this, address))
123 CRITICAL_BLOCK(cs_wallet)
124 if (!mapAddressBook.count(address))
128 int64 GetChange(const CTxOut& txout) const
130 if (!MoneyRange(txout.nValue))
131 throw std::runtime_error("CWallet::GetChange() : value out of range");
132 return (IsChange(txout) ? txout.nValue : 0);
134 bool IsMine(const CTransaction& tx) const
136 BOOST_FOREACH(const CTxOut& txout, tx.vout)
141 bool IsFromMe(const CTransaction& tx) const
143 return (GetDebit(tx) > 0);
145 int64 GetDebit(const CTransaction& tx) const
148 BOOST_FOREACH(const CTxIn& txin, tx.vin)
150 nDebit += GetDebit(txin);
151 if (!MoneyRange(nDebit))
152 throw std::runtime_error("CWallet::GetDebit() : value out of range");
156 int64 GetCredit(const CTransaction& tx) const
159 BOOST_FOREACH(const CTxOut& txout, tx.vout)
161 nCredit += GetCredit(txout);
162 if (!MoneyRange(nCredit))
163 throw std::runtime_error("CWallet::GetCredit() : value out of range");
167 int64 GetChange(const CTransaction& tx) const
170 BOOST_FOREACH(const CTxOut& txout, tx.vout)
172 nChange += GetChange(txout);
173 if (!MoneyRange(nChange))
174 throw std::runtime_error("CWallet::GetChange() : value out of range");
178 void SetBestChain(const CBlockLocator& loc)
180 CWalletDB walletdb(strWalletFile);
181 walletdb.WriteBestBlock(loc);
184 int LoadWallet(bool& fFirstRunRet);
185 // bool BackupWallet(const std::string& strDest);
187 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
189 bool DelAddressBookName(const CBitcoinAddress& address);
191 void UpdatedTransaction(const uint256 &hashTx)
193 CRITICAL_BLOCK(cs_wallet)
194 vWalletUpdated.push_back(hashTx);
197 void PrintWallet(const CBlock& block);
199 void Inventory(const uint256 &hash)
201 CRITICAL_BLOCK(cs_wallet)
203 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
204 if (mi != mapRequestCount.end())
211 return setKeyPool.size();
214 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
216 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
218 bool CheckSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion);
219 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion);
220 void DisableTransaction(const CTransaction &tx);
229 std::vector<unsigned char> vchPubKey;
231 CReserveKey(CWallet* pwalletIn)
244 std::vector<unsigned char> GetReservedKey();
250 // A transaction with a bunch of additional info that only the owner cares
251 // about. It includes any unrecorded transactions needed to link it back
252 // to the block chain.
254 class CWalletTx : public CMerkleTx
257 const CWallet* pwallet;
259 std::vector<CMerkleTx> vtxPrev;
260 std::map<std::string, std::string> mapValue;
261 std::vector<std::pair<std::string, std::string> > vOrderForm;
262 unsigned int fTimeReceivedIsTxTime;
263 unsigned int nTimeReceived; // time received by this node
265 std::string strFromAccount;
266 std::vector<char> vfSpent; // which outputs are already spent
269 mutable char fDebitCached;
270 mutable char fCreditCached;
271 mutable char fAvailableCreditCached;
272 mutable char fChangeCached;
273 mutable int64 nDebitCached;
274 mutable int64 nCreditCached;
275 mutable int64 nAvailableCreditCached;
276 mutable int64 nChangeCached;
278 // memory only UI hints
279 mutable unsigned int nTimeDisplayed;
280 mutable int nLinesDisplayed;
281 mutable char fConfirmedDisplayed;
288 CWalletTx(const CWallet* pwalletIn)
293 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
298 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
303 void Init(const CWallet* pwalletIn)
309 fTimeReceivedIsTxTime = false;
312 strFromAccount.clear();
314 fDebitCached = false;
315 fCreditCached = false;
316 fAvailableCreditCached = false;
317 fChangeCached = false;
320 nAvailableCreditCached = 0;
324 fConfirmedDisplayed = false;
329 CWalletTx* pthis = const_cast<CWalletTx*>(this);
336 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
339 BOOST_FOREACH(char f, vfSpent)
341 str += (f ? '1' : '0');
345 pthis->mapValue["spent"] = str;
348 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
351 READWRITE(vOrderForm);
352 READWRITE(fTimeReceivedIsTxTime);
353 READWRITE(nTimeReceived);
359 pthis->strFromAccount = pthis->mapValue["fromaccount"];
361 if (mapValue.count("spent"))
362 BOOST_FOREACH(char c, pthis->mapValue["spent"])
363 pthis->vfSpent.push_back(c != '0');
365 pthis->vfSpent.assign(vout.size(), fSpent);
368 pthis->mapValue.erase("fromaccount");
369 pthis->mapValue.erase("version");
370 pthis->mapValue.erase("spent");
373 // marks certain txout's as spent
374 // returns true if any update took place
375 bool UpdateSpent(const std::vector<char>& vfNewSpent)
377 bool fReturn = false;
378 for (int i=0; i < vfNewSpent.size(); i++)
380 if (i == vfSpent.size())
383 if (vfNewSpent[i] && !vfSpent[i])
387 fAvailableCreditCached = false;
393 // make sure balances are recalculated
396 fCreditCached = false;
397 fAvailableCreditCached = false;
398 fDebitCached = false;
399 fChangeCached = false;
402 void MarkSpent(unsigned int nOut)
404 if (nOut >= vout.size())
405 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
406 vfSpent.resize(vout.size());
409 vfSpent[nOut] = true;
410 fAvailableCreditCached = false;
414 void MarkUnspent(unsigned int nOut)
416 if (nOut >= vout.size())
417 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
418 vfSpent.resize(vout.size());
421 vfSpent[nOut] = false;
422 fAvailableCreditCached = false;
426 bool IsSpent(unsigned int nOut) const
428 if (nOut >= vout.size())
429 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
430 if (nOut >= vfSpent.size())
432 return (!!vfSpent[nOut]);
435 int64 GetDebit() const
441 nDebitCached = pwallet->GetDebit(*this);
446 int64 GetCredit(bool fUseCache=true) const
448 // Must wait until coinbase is safely deep enough in the chain before valuing it
449 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
452 // GetBalance can assume transactions in mapWallet won't change
453 if (fUseCache && fCreditCached)
454 return nCreditCached;
455 nCreditCached = pwallet->GetCredit(*this);
456 fCreditCached = true;
457 return nCreditCached;
460 int64 GetAvailableCredit(bool fUseCache=true) const
462 // Must wait until coinbase is safely deep enough in the chain before valuing it
463 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
466 if (fUseCache && fAvailableCreditCached)
467 return nAvailableCreditCached;
470 for (int i = 0; i < vout.size(); i++)
474 const CTxOut &txout = vout[i];
475 nCredit += pwallet->GetCredit(txout);
476 if (!MoneyRange(nCredit))
477 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
481 nAvailableCreditCached = nCredit;
482 fAvailableCreditCached = true;
487 int64 GetChange() const
490 return nChangeCached;
491 nChangeCached = pwallet->GetChange(*this);
492 fChangeCached = true;
493 return nChangeCached;
496 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
497 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
499 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
500 int64& nSent, int64& nFee) const;
502 bool IsFromMe() const
504 return (GetDebit() > 0);
507 bool IsConfirmed() const
509 // Quick answer in most cases
512 if (GetDepthInMainChain() >= 1)
514 if (!IsFromMe()) // using wtx's cached debit
517 // If no confirmations but it's from us, we can still
518 // consider it confirmed if all dependencies are confirmed
519 std::map<uint256, const CMerkleTx*> mapPrev;
520 std::vector<const CMerkleTx*> vWorkQueue;
521 vWorkQueue.reserve(vtxPrev.size()+1);
522 vWorkQueue.push_back(this);
523 for (int i = 0; i < vWorkQueue.size(); i++)
525 const CMerkleTx* ptx = vWorkQueue[i];
529 if (ptx->GetDepthInMainChain() >= 1)
531 if (!pwallet->IsFromMe(*ptx))
535 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
536 mapPrev[tx.GetHash()] = &tx;
538 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
540 if (!mapPrev.count(txin.prevout.hash))
542 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
550 int64 GetTxTime() const;
551 int GetRequestCount() const;
553 void AddSupportingTransactions(CTxDB& txdb);
555 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
556 bool AcceptWalletTransaction();
558 void RelayWalletTransaction(CTxDB& txdb);
559 void RelayWalletTransaction();
564 // Private key that includes an expiration date in case it never gets used.
572 std::string strComment;
573 //// todo: add something to note what created it (user, getnewaddress, change)
574 //// maybe should have a map<string, string> property map
576 CWalletKey(int64 nExpires=0)
578 nTimeCreated = (nExpires ? GetTime() : 0);
579 nTimeExpires = nExpires;
584 if (!(nType & SER_GETHASH))
586 READWRITE(vchPrivKey);
587 READWRITE(nTimeCreated);
588 READWRITE(nTimeExpires);
589 READWRITE(strComment);
599 // Account information.
600 // Stored in wallet with key "acc"+string account name
605 std::vector<unsigned char> vchPubKey;
619 if (!(nType & SER_GETHASH))
621 READWRITE(vchPubKey);
628 // Internal transfers.
629 // Database key is acentry<account><counter>
631 class CAccountingEntry
634 std::string strAccount;
637 std::string strOtherAccount;
638 std::string strComment;
650 strOtherAccount.clear();
656 if (!(nType & SER_GETHASH))
658 // Note: strAccount is serialized as part of the key, not here.
659 READWRITE(nCreditDebit);
661 READWRITE(strOtherAccount);
662 READWRITE(strComment);
666 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);