1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_WALLET_H
7 #define BITCOIN_WALLET_H
14 extern bool fWalletUnlockMintOnly;
20 /** (client) version numbers for particular wallet features */
23 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
25 FEATURE_WALLETCRYPT = 40000, // wallet encryption
26 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
28 FEATURE_LATEST = 60000
32 /** A key pool entry */
37 std::vector<unsigned char> vchPubKey;
44 CKeyPool(const std::vector<unsigned char>& vchPubKeyIn)
47 vchPubKey = vchPubKeyIn;
52 if (!(nType & SER_GETHASH))
59 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
60 * and provides the ability to create new transactions.
62 class CWallet : public CCryptoKeyStore
65 bool SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
66 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
68 CWalletDB *pwalletdbEncryption;
70 // the current wallet version: clients below this version are not able to load the wallet
73 // the maxmimum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
74 int nWalletMaxVersion;
77 mutable CCriticalSection cs_wallet;
80 std::string strWalletFile;
82 std::set<int64> setKeyPool;
85 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
86 MasterKeyMap mapMasterKeys;
87 unsigned int nMasterKeyMaxID;
91 nWalletVersion = FEATURE_BASE;
92 nWalletMaxVersion = FEATURE_BASE;
95 pwalletdbEncryption = NULL;
97 CWallet(std::string strWalletFileIn)
99 nWalletVersion = FEATURE_BASE;
100 nWalletMaxVersion = FEATURE_BASE;
101 strWalletFile = strWalletFileIn;
104 pwalletdbEncryption = NULL;
107 std::map<uint256, CWalletTx> mapWallet;
108 std::vector<uint256> vWalletUpdated;
110 std::map<uint256, int> mapRequestCount;
112 std::map<CBitcoinAddress, std::string> mapAddressBook;
114 std::vector<unsigned char> vchDefaultKey;
116 // check whether we are allowed to upgrade (or already support) to the named feature
117 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
119 // keystore implementation
120 // Generate a new key
121 std::vector<unsigned char> GenerateNewKey();
122 // Adds a key to the store, and saves it to disk.
123 bool AddKey(const CKey& key);
124 // Adds a key to the store, without saving it to disk (used by LoadWallet)
125 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
127 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
129 // Adds an encrypted key to the store, and saves it to disk.
130 bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
131 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
132 bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
133 bool AddCScript(const CScript& redeemScript);
134 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
136 bool Unlock(const SecureString& strWalletPassphrase);
137 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
138 bool EncryptWallet(const SecureString& strWalletPassphrase);
141 bool AddToWallet(const CWalletTx& wtxIn);
142 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
143 bool EraseFromWallet(uint256 hash);
144 void WalletUpdateSpent(const CTransaction& prevout);
145 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
146 int ScanForWalletTransaction(const uint256& hashTx);
147 void ReacceptWalletTransactions();
148 void ResendWalletTransactions();
149 int64 GetBalance() const;
150 int64 GetUnconfirmedBalance() const;
151 int64 GetStake() const;
152 int64 GetNewMint() const;
153 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
154 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
155 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, CTransaction& txNew);
156 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
157 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
158 std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
162 int64 AddReserveKey(const CKeyPool& keypool);
163 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
164 void KeepKey(int64 nIndex);
165 void ReturnKey(int64 nIndex);
166 bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
167 int64 GetOldestKeyPoolTime();
168 void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
170 bool IsMine(const CTxIn& txin) const;
171 int64 GetDebit(const CTxIn& txin) const;
172 bool IsMine(const CTxOut& txout) const
174 return ::IsMine(*this, txout.scriptPubKey);
176 int64 GetCredit(const CTxOut& txout) const
178 if (!MoneyRange(txout.nValue))
179 throw std::runtime_error("CWallet::GetCredit() : value out of range");
180 return (IsMine(txout) ? txout.nValue : 0);
182 bool IsChange(const CTxOut& txout) const;
183 int64 GetChange(const CTxOut& txout) const
185 if (!MoneyRange(txout.nValue))
186 throw std::runtime_error("CWallet::GetChange() : value out of range");
187 return (IsChange(txout) ? txout.nValue : 0);
189 bool IsMine(const CTransaction& tx) const
191 BOOST_FOREACH(const CTxOut& txout, tx.vout)
196 bool IsFromMe(const CTransaction& tx) const
198 return (GetDebit(tx) > 0);
200 int64 GetDebit(const CTransaction& tx) const
203 BOOST_FOREACH(const CTxIn& txin, tx.vin)
205 nDebit += GetDebit(txin);
206 if (!MoneyRange(nDebit))
207 throw std::runtime_error("CWallet::GetDebit() : value out of range");
211 int64 GetCredit(const CTransaction& tx) const
214 BOOST_FOREACH(const CTxOut& txout, tx.vout)
216 nCredit += GetCredit(txout);
217 if (!MoneyRange(nCredit))
218 throw std::runtime_error("CWallet::GetCredit() : value out of range");
222 int64 GetChange(const CTransaction& tx) const
225 BOOST_FOREACH(const CTxOut& txout, tx.vout)
227 nChange += GetChange(txout);
228 if (!MoneyRange(nChange))
229 throw std::runtime_error("CWallet::GetChange() : value out of range");
233 void SetBestChain(const CBlockLocator& loc);
235 int LoadWallet(bool& fFirstRunRet);
237 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
239 bool DelAddressBookName(const CBitcoinAddress& address);
241 void UpdatedTransaction(const uint256 &hashTx)
245 vWalletUpdated.push_back(hashTx);
249 void PrintWallet(const CBlock& block);
251 void Inventory(const uint256 &hash)
255 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
256 if (mi != mapRequestCount.end())
263 return setKeyPool.size();
266 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
268 bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
270 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
271 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
273 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
274 bool SetMaxVersion(int nVersion);
276 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
277 int GetVersion() { return nWalletVersion; }
279 bool CheckSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion);
280 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion);
281 void DisableTransaction(const CTransaction &tx);
284 /** A key allocated from the key pool. */
290 std::vector<unsigned char> vchPubKey;
292 CReserveKey(CWallet* pwalletIn)
305 std::vector<unsigned char> GetReservedKey();
310 /** A transaction with a bunch of additional info that only the owner cares about.
311 * It includes any unrecorded transactions needed to link it back to the block chain.
313 class CWalletTx : public CMerkleTx
316 const CWallet* pwallet;
319 std::vector<CMerkleTx> vtxPrev;
320 std::map<std::string, std::string> mapValue;
321 std::vector<std::pair<std::string, std::string> > vOrderForm;
322 unsigned int fTimeReceivedIsTxTime;
323 unsigned int nTimeReceived; // time received by this node
325 std::string strFromAccount;
326 std::vector<char> vfSpent; // which outputs are already spent
329 mutable bool fDebitCached;
330 mutable bool fCreditCached;
331 mutable bool fAvailableCreditCached;
332 mutable bool fChangeCached;
333 mutable int64 nDebitCached;
334 mutable int64 nCreditCached;
335 mutable int64 nAvailableCreditCached;
336 mutable int64 nChangeCached;
343 CWalletTx(const CWallet* pwalletIn)
348 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
353 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
358 void Init(const CWallet* pwalletIn)
364 fTimeReceivedIsTxTime = false;
367 strFromAccount.clear();
369 fDebitCached = false;
370 fCreditCached = false;
371 fAvailableCreditCached = false;
372 fChangeCached = false;
375 nAvailableCreditCached = 0;
381 CWalletTx* pthis = const_cast<CWalletTx*>(this);
388 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
391 BOOST_FOREACH(char f, vfSpent)
393 str += (f ? '1' : '0');
397 pthis->mapValue["spent"] = str;
400 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
403 READWRITE(vOrderForm);
404 READWRITE(fTimeReceivedIsTxTime);
405 READWRITE(nTimeReceived);
411 pthis->strFromAccount = pthis->mapValue["fromaccount"];
413 if (mapValue.count("spent"))
414 BOOST_FOREACH(char c, pthis->mapValue["spent"])
415 pthis->vfSpent.push_back(c != '0');
417 pthis->vfSpent.assign(vout.size(), fSpent);
420 pthis->mapValue.erase("fromaccount");
421 pthis->mapValue.erase("version");
422 pthis->mapValue.erase("spent");
425 // marks certain txout's as spent
426 // returns true if any update took place
427 bool UpdateSpent(const std::vector<char>& vfNewSpent)
429 bool fReturn = false;
430 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
432 if (i == vfSpent.size())
435 if (vfNewSpent[i] && !vfSpent[i])
439 fAvailableCreditCached = false;
445 // make sure balances are recalculated
448 fCreditCached = false;
449 fAvailableCreditCached = false;
450 fDebitCached = false;
451 fChangeCached = false;
454 void BindWallet(CWallet *pwalletIn)
460 void MarkSpent(unsigned int nOut)
462 if (nOut >= vout.size())
463 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
464 vfSpent.resize(vout.size());
467 vfSpent[nOut] = true;
468 fAvailableCreditCached = false;
472 void MarkUnspent(unsigned int nOut)
474 if (nOut >= vout.size())
475 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
476 vfSpent.resize(vout.size());
479 vfSpent[nOut] = false;
480 fAvailableCreditCached = false;
484 bool IsSpent(unsigned int nOut) const
486 if (nOut >= vout.size())
487 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
488 if (nOut >= vfSpent.size())
490 return (!!vfSpent[nOut]);
493 int64 GetDebit() const
499 nDebitCached = pwallet->GetDebit(*this);
504 int64 GetCredit(bool fUseCache=true) const
506 // Must wait until coinbase is safely deep enough in the chain before valuing it
507 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
510 // GetBalance can assume transactions in mapWallet won't change
511 if (fUseCache && fCreditCached)
512 return nCreditCached;
513 nCreditCached = pwallet->GetCredit(*this);
514 fCreditCached = true;
515 return nCreditCached;
518 int64 GetAvailableCredit(bool fUseCache=true) const
520 // Must wait until coinbase is safely deep enough in the chain before valuing it
521 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
524 if (fUseCache && fAvailableCreditCached)
525 return nAvailableCreditCached;
528 for (unsigned int i = 0; i < vout.size(); i++)
532 const CTxOut &txout = vout[i];
533 nCredit += pwallet->GetCredit(txout);
534 if (!MoneyRange(nCredit))
535 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
539 nAvailableCreditCached = nCredit;
540 fAvailableCreditCached = true;
545 int64 GetChange() const
548 return nChangeCached;
549 nChangeCached = pwallet->GetChange(*this);
550 fChangeCached = true;
551 return nChangeCached;
554 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
555 std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
557 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
558 int64& nSent, int64& nFee) const;
560 bool IsFromMe() const
562 return (GetDebit() > 0);
565 bool IsConfirmed() const
567 // Quick answer in most cases
570 if (GetDepthInMainChain() >= 1)
572 if (!IsFromMe()) // using wtx's cached debit
575 // If no confirmations but it's from us, we can still
576 // consider it confirmed if all dependencies are confirmed
577 std::map<uint256, const CMerkleTx*> mapPrev;
578 std::vector<const CMerkleTx*> vWorkQueue;
579 vWorkQueue.reserve(vtxPrev.size()+1);
580 vWorkQueue.push_back(this);
581 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
583 const CMerkleTx* ptx = vWorkQueue[i];
587 if (ptx->GetDepthInMainChain() >= 1)
589 if (!pwallet->IsFromMe(*ptx))
594 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
595 mapPrev[tx.GetHash()] = &tx;
598 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
600 if (!mapPrev.count(txin.prevout.hash))
602 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
610 int64 GetTxTime() const;
611 int GetRequestCount() const;
613 void AddSupportingTransactions(CTxDB& txdb);
615 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
616 bool AcceptWalletTransaction();
618 void RelayWalletTransaction(CTxDB& txdb);
619 void RelayWalletTransaction();
623 /** Private key that includes an expiration date in case it never gets used. */
630 std::string strComment;
631 //// todo: add something to note what created it (user, getnewaddress, change)
632 //// maybe should have a map<string, string> property map
634 CWalletKey(int64 nExpires=0)
636 nTimeCreated = (nExpires ? GetTime() : 0);
637 nTimeExpires = nExpires;
642 if (!(nType & SER_GETHASH))
644 READWRITE(vchPrivKey);
645 READWRITE(nTimeCreated);
646 READWRITE(nTimeExpires);
647 READWRITE(strComment);
656 /** Account information.
657 * Stored in wallet with key "acc"+string account name.
662 std::vector<unsigned char> vchPubKey;
676 if (!(nType & SER_GETHASH))
678 READWRITE(vchPubKey);
684 /** Internal transfers.
685 * Database key is acentry<account><counter>.
687 class CAccountingEntry
690 std::string strAccount;
693 std::string strOtherAccount;
694 std::string strComment;
706 strOtherAccount.clear();
712 if (!(nType & SER_GETHASH))
714 // Note: strAccount is serialized as part of the key, not here.
715 READWRITE(nCreditDebit);
717 READWRITE(strOtherAccount);
718 READWRITE(strComment);
722 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);