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 COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_WALLET_H
6 #define BITCOIN_WALLET_H
17 #include "ui_interface.h"
21 extern bool fWalletUnlockMintOnly;
22 class CAccountingEntry;
27 /** (client) version numbers for particular wallet features */
30 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
32 FEATURE_WALLETCRYPT = 40000, // wallet encryption
33 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
35 FEATURE_LATEST = 60000
38 /** Stake weight calculation mode */
41 STAKE_NORMAL = 0, // all 30+ days old inputs
42 STAKE_MAXWEIGHT = 1, // only 90+ days old inputs
43 STAKE_MINWEIGHT = 3 // only [30-90] days old inputs
46 /** A key pool entry */
58 CKeyPool(const CPubKey& vchPubKeyIn)
61 vchPubKey = vchPubKeyIn;
66 if (!(nType & SER_GETHASH))
73 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
74 * and provides the ability to create new transactions.
76 class CWallet : public CCryptoKeyStore
79 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
81 CWalletDB *pwalletdbEncryption;
83 // the current wallet version: clients below this version are not able to load the wallet
86 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
87 int nWalletMaxVersion;
90 mutable CCriticalSection cs_wallet;
93 std::string strWalletFile;
95 std::set<int64> setKeyPool;
96 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
99 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
100 MasterKeyMap mapMasterKeys;
101 unsigned int nMasterKeyMaxID;
105 nWalletVersion = FEATURE_BASE;
106 nWalletMaxVersion = FEATURE_BASE;
109 pwalletdbEncryption = NULL;
112 CWallet(std::string strWalletFileIn)
114 nWalletVersion = FEATURE_BASE;
115 nWalletMaxVersion = FEATURE_BASE;
116 strWalletFile = strWalletFileIn;
119 pwalletdbEncryption = NULL;
123 std::map<uint256, CWalletTx> mapWallet;
125 std::map<uint256, int> mapRequestCount;
127 std::map<CTxDestination, std::string> mapAddressBook;
129 CPubKey vchDefaultKey;
132 // check whether we are allowed to upgrade (or already support) to the named feature
133 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
135 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true) const;
136 bool SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
137 // keystore implementation
138 // Generate a new key
139 CPubKey GenerateNewKey();
140 // Adds a key to the store, and saves it to disk.
141 bool AddKey(const CKey& key);
142 // Adds a key to the store, without saving it to disk (used by LoadWallet)
143 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
144 // Load metadata (used by LoadWallet)
145 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
147 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
149 // Adds an encrypted key to the store, and saves it to disk.
150 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
151 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
152 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
153 bool AddCScript(const CScript& redeemScript);
154 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
156 bool Unlock(const SecureString& strWalletPassphrase);
157 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
158 bool EncryptWallet(const SecureString& strWalletPassphrase);
160 void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
163 /** Increment the next transaction order id
164 @return next transaction order id
166 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
168 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
169 typedef std::multimap<int64, TxPair > TxItems;
171 /** Get the wallet's activity log
172 @return multimap of ordered transactions and accounting entries
173 @warning Returned pointers are *only* valid within the scope of passed acentries
175 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
178 bool AddToWallet(const CWalletTx& wtxIn);
179 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
180 bool EraseFromWallet(uint256 hash);
181 void WalletUpdateSpent(const CTransaction& prevout);
182 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
183 int ScanForWalletTransaction(const uint256& hashTx);
184 void ReacceptWalletTransactions();
185 void ResendWalletTransactions();
186 int64 GetBalance() const;
187 int64 GetUnconfirmedBalance() const;
188 int64 GetImmatureBalance() const;
189 int64 GetStake() const;
190 int64 GetNewMint() const;
191 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
192 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
193 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
195 uint64 GetStakeWeight(const CKeyStore& keystore, enum StakeWeightMode mode=STAKE_NORMAL);
196 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew);
198 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
199 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
202 bool TopUpKeyPool(unsigned int nSize = 0);
203 int64 AddReserveKey(const CKeyPool& keypool);
204 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
205 void KeepKey(int64 nIndex);
206 void ReturnKey(int64 nIndex);
207 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
208 int64 GetOldestKeyPoolTime();
209 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
211 std::set< std::set<CTxDestination> > GetAddressGroupings();
212 std::map<CTxDestination, int64> GetAddressBalances();
214 bool IsMine(const CTxIn& txin) const;
215 int64 GetDebit(const CTxIn& txin) const;
216 bool IsMine(const CTxOut& txout) const
218 return ::IsMine(*this, txout.scriptPubKey);
220 int64 GetCredit(const CTxOut& txout) const
222 if (!MoneyRange(txout.nValue))
223 throw std::runtime_error("CWallet::GetCredit() : value out of range");
224 return (IsMine(txout) ? txout.nValue : 0);
226 bool IsChange(const CTxOut& txout) const;
227 int64 GetChange(const CTxOut& txout) const
229 if (!MoneyRange(txout.nValue))
230 throw std::runtime_error("CWallet::GetChange() : value out of range");
231 return (IsChange(txout) ? txout.nValue : 0);
233 bool IsMine(const CTransaction& tx) const
235 BOOST_FOREACH(const CTxOut& txout, tx.vout)
240 bool IsFromMe(const CTransaction& tx) const
242 return (GetDebit(tx) > 0);
244 int64 GetDebit(const CTransaction& tx) const
247 BOOST_FOREACH(const CTxIn& txin, tx.vin)
249 nDebit += GetDebit(txin);
250 if (!MoneyRange(nDebit))
251 throw std::runtime_error("CWallet::GetDebit() : value out of range");
255 int64 GetCredit(const CTransaction& tx) const
258 BOOST_FOREACH(const CTxOut& txout, tx.vout)
260 nCredit += GetCredit(txout);
261 if (!MoneyRange(nCredit))
262 throw std::runtime_error("CWallet::GetCredit() : value out of range");
266 int64 GetChange(const CTransaction& tx) const
269 BOOST_FOREACH(const CTxOut& txout, tx.vout)
271 nChange += GetChange(txout);
272 if (!MoneyRange(nChange))
273 throw std::runtime_error("CWallet::GetChange() : value out of range");
277 void SetBestChain(const CBlockLocator& loc);
279 DBErrors LoadWallet(bool& fFirstRunRet);
281 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
283 bool DelAddressBookName(const CTxDestination& address);
285 void UpdatedTransaction(const uint256 &hashTx);
287 void PrintWallet(const CBlock& block);
289 void Inventory(const uint256 &hash)
293 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
294 if (mi != mapRequestCount.end())
299 unsigned int GetKeyPoolSize()
301 return setKeyPool.size();
304 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
306 bool SetDefaultKey(const CPubKey &vchPubKey);
308 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
309 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
311 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
312 bool SetMaxVersion(int nVersion);
314 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
315 int GetVersion() { return nWalletVersion; }
317 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
318 void DisableTransaction(const CTransaction &tx);
320 /** Address book entry changed.
321 * @note called with lock cs_wallet held.
323 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
325 /** Wallet transaction added, removed or updated.
326 * @note called with lock cs_wallet held.
328 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
331 /** A key allocated from the key pool. */
339 CReserveKey(CWallet* pwalletIn)
352 CPubKey GetReservedKey();
357 typedef std::map<std::string, std::string> mapValue_t;
360 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
362 if (!mapValue.count("n"))
364 nOrderPos = -1; // TODO: calculate elsewhere
367 nOrderPos = atoi64(mapValue["n"].c_str());
371 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
375 mapValue["n"] = i64tostr(nOrderPos);
379 /** A transaction with a bunch of additional info that only the owner cares about.
380 * It includes any unrecorded transactions needed to link it back to the block chain.
382 class CWalletTx : public CMerkleTx
385 const CWallet* pwallet;
388 std::vector<CMerkleTx> vtxPrev;
390 std::vector<std::pair<std::string, std::string> > vOrderForm;
391 unsigned int fTimeReceivedIsTxTime;
392 unsigned int nTimeReceived; // time received by this node
393 unsigned int nTimeSmart;
395 std::string strFromAccount;
396 std::vector<char> vfSpent; // which outputs are already spent
397 int64 nOrderPos; // position in ordered transaction list
400 mutable bool fDebitCached;
401 mutable bool fCreditCached;
402 mutable bool fAvailableCreditCached;
403 mutable bool fChangeCached;
404 mutable int64 nDebitCached;
405 mutable int64 nCreditCached;
406 mutable int64 nAvailableCreditCached;
407 mutable int64 nChangeCached;
414 CWalletTx(const CWallet* pwalletIn)
419 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
424 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
429 void Init(const CWallet* pwalletIn)
435 fTimeReceivedIsTxTime = false;
439 strFromAccount.clear();
441 fDebitCached = false;
442 fCreditCached = false;
443 fAvailableCreditCached = false;
444 fChangeCached = false;
447 nAvailableCreditCached = 0;
454 CWalletTx* pthis = const_cast<CWalletTx*>(this);
461 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
464 BOOST_FOREACH(char f, vfSpent)
466 str += (f ? '1' : '0');
470 pthis->mapValue["spent"] = str;
472 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
475 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
478 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
481 READWRITE(vOrderForm);
482 READWRITE(fTimeReceivedIsTxTime);
483 READWRITE(nTimeReceived);
489 pthis->strFromAccount = pthis->mapValue["fromaccount"];
491 if (mapValue.count("spent"))
492 BOOST_FOREACH(char c, pthis->mapValue["spent"])
493 pthis->vfSpent.push_back(c != '0');
495 pthis->vfSpent.assign(vout.size(), fSpent);
497 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
499 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
502 pthis->mapValue.erase("fromaccount");
503 pthis->mapValue.erase("version");
504 pthis->mapValue.erase("spent");
505 pthis->mapValue.erase("n");
506 pthis->mapValue.erase("timesmart");
509 // marks certain txout's as spent
510 // returns true if any update took place
511 bool UpdateSpent(const std::vector<char>& vfNewSpent)
513 bool fReturn = false;
514 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
516 if (i == vfSpent.size())
519 if (vfNewSpent[i] && !vfSpent[i])
523 fAvailableCreditCached = false;
529 // make sure balances are recalculated
532 fCreditCached = false;
533 fAvailableCreditCached = false;
534 fDebitCached = false;
535 fChangeCached = false;
538 void BindWallet(CWallet *pwalletIn)
544 void MarkSpent(unsigned int nOut)
546 if (nOut >= vout.size())
547 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
548 vfSpent.resize(vout.size());
551 vfSpent[nOut] = true;
552 fAvailableCreditCached = false;
556 void MarkUnspent(unsigned int nOut)
558 if (nOut >= vout.size())
559 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
560 vfSpent.resize(vout.size());
563 vfSpent[nOut] = false;
564 fAvailableCreditCached = false;
568 bool IsSpent(unsigned int nOut) const
570 if (nOut >= vout.size())
571 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
572 if (nOut >= vfSpent.size())
574 return (!!vfSpent[nOut]);
577 int64 GetDebit() const
583 nDebitCached = pwallet->GetDebit(*this);
588 int64 GetCredit(bool fUseCache=true) const
590 // Must wait until coinbase is safely deep enough in the chain before valuing it
591 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
594 // GetBalance can assume transactions in mapWallet won't change
595 if (fUseCache && fCreditCached)
596 return nCreditCached;
597 nCreditCached = pwallet->GetCredit(*this);
598 fCreditCached = true;
599 return nCreditCached;
602 int64 GetAvailableCredit(bool fUseCache=true) const
604 // Must wait until coinbase is safely deep enough in the chain before valuing it
605 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
608 if (fUseCache && fAvailableCreditCached)
609 return nAvailableCreditCached;
612 for (unsigned int i = 0; i < vout.size(); i++)
616 const CTxOut &txout = vout[i];
617 nCredit += pwallet->GetCredit(txout);
618 if (!MoneyRange(nCredit))
619 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
623 nAvailableCreditCached = nCredit;
624 fAvailableCreditCached = true;
629 int64 GetChange() const
632 return nChangeCached;
633 nChangeCached = pwallet->GetChange(*this);
634 fChangeCached = true;
635 return nChangeCached;
638 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
639 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
641 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
642 int64& nSent, int64& nFee) const;
644 bool IsFromMe() const
646 return (GetDebit() > 0);
649 bool IsConfirmed() const
651 // Quick answer in most cases
654 if (GetDepthInMainChain() >= 1)
656 if (!IsFromMe()) // using wtx's cached debit
659 // If no confirmations but it's from us, we can still
660 // consider it confirmed if all dependencies are confirmed
661 std::map<uint256, const CMerkleTx*> mapPrev;
662 std::vector<const CMerkleTx*> vWorkQueue;
663 vWorkQueue.reserve(vtxPrev.size()+1);
664 vWorkQueue.push_back(this);
665 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
667 const CMerkleTx* ptx = vWorkQueue[i];
671 if (ptx->GetDepthInMainChain() >= 1)
673 if (!pwallet->IsFromMe(*ptx))
678 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
679 mapPrev[tx.GetHash()] = &tx;
682 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
684 if (!mapPrev.count(txin.prevout.hash))
686 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
694 int64 GetTxTime() const;
695 int GetRequestCount() const;
697 void AddSupportingTransactions(CTxDB& txdb);
699 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
700 bool AcceptWalletTransaction();
702 void RelayWalletTransaction(CTxDB& txdb);
703 void RelayWalletTransaction();
716 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
718 tx = txIn; i = iIn; nDepth = nDepthIn;
721 std::string ToString() const
723 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
728 printf("%s\n", ToString().c_str());
735 /** Private key that includes an expiration date in case it never gets used. */
742 std::string strComment;
743 //// todo: add something to note what created it (user, getnewaddress, change)
744 //// maybe should have a map<string, string> property map
746 CWalletKey(int64 nExpires=0)
748 nTimeCreated = (nExpires ? GetTime() : 0);
749 nTimeExpires = nExpires;
754 if (!(nType & SER_GETHASH))
756 READWRITE(vchPrivKey);
757 READWRITE(nTimeCreated);
758 READWRITE(nTimeExpires);
759 READWRITE(strComment);
768 /** Account information.
769 * Stored in wallet with key "acc"+string account name.
783 vchPubKey = CPubKey();
788 if (!(nType & SER_GETHASH))
790 READWRITE(vchPubKey);
796 /** Internal transfers.
797 * Database key is acentry<account><counter>.
799 class CAccountingEntry
802 std::string strAccount;
805 std::string strOtherAccount;
806 std::string strComment;
808 int64 nOrderPos; // position in ordered transaction list
821 strOtherAccount.clear();
828 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
829 if (!(nType & SER_GETHASH))
831 // Note: strAccount is serialized as part of the key, not here.
832 READWRITE(nCreditDebit);
834 READWRITE(strOtherAccount);
838 WriteOrderPos(nOrderPos, me.mapValue);
840 if (!(mapValue.empty() && _ssExtra.empty()))
842 CDataStream ss(nType, nVersion);
843 ss.insert(ss.begin(), '\0');
845 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
846 me.strComment.append(ss.str());
850 READWRITE(strComment);
852 size_t nSepPos = strComment.find("\0", 0, 1);
856 if (std::string::npos != nSepPos)
858 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
860 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
862 ReadOrderPos(me.nOrderPos, me.mapValue);
864 if (std::string::npos != nSepPos)
865 me.strComment.erase(nSepPos);
867 me.mapValue.erase("n");
871 std::vector<char> _ssExtra;
874 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);