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
44 STAKE_BELOWMIN = 4 // only less than 30 days old inputs
47 /** A key pool entry */
59 CKeyPool(const CPubKey& vchPubKeyIn)
62 vchPubKey = vchPubKeyIn;
67 if (!(nType & SER_GETHASH))
74 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
75 * and provides the ability to create new transactions.
77 class CWallet : public CCryptoKeyStore
80 bool SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
82 CWalletDB *pwalletdbEncryption;
84 // the current wallet version: clients below this version are not able to load the wallet
87 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
88 int nWalletMaxVersion;
91 mutable CCriticalSection cs_wallet;
94 std::string strWalletFile;
96 std::set<int64> setKeyPool;
97 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
100 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
101 MasterKeyMap mapMasterKeys;
102 unsigned int nMasterKeyMaxID;
106 nWalletVersion = FEATURE_BASE;
107 nWalletMaxVersion = FEATURE_BASE;
110 pwalletdbEncryption = NULL;
113 CWallet(std::string strWalletFileIn)
115 nWalletVersion = FEATURE_BASE;
116 nWalletMaxVersion = FEATURE_BASE;
117 strWalletFile = strWalletFileIn;
120 pwalletdbEncryption = NULL;
124 std::map<uint256, CWalletTx> mapWallet;
126 std::map<uint256, int> mapRequestCount;
128 std::map<CTxDestination, std::string> mapAddressBook;
130 CPubKey vchDefaultKey;
133 // check whether we are allowed to upgrade (or already support) to the named feature
134 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
136 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true) const;
137 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;
138 // keystore implementation
139 // Generate a new key
140 CPubKey GenerateNewKey();
141 // Adds a key to the store, and saves it to disk.
142 bool AddKey(const CKey& key);
143 // Adds a key to the store, without saving it to disk (used by LoadWallet)
144 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
145 // Load metadata (used by LoadWallet)
146 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
148 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
150 // Adds an encrypted key to the store, and saves it to disk.
151 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
152 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
153 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
154 bool AddCScript(const CScript& redeemScript);
155 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
157 bool Unlock(const SecureString& strWalletPassphrase);
158 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
159 bool EncryptWallet(const SecureString& strWalletPassphrase);
161 void GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const;
164 /** Increment the next transaction order id
165 @return next transaction order id
167 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
169 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
170 typedef std::multimap<int64, TxPair > TxItems;
172 /** Get the wallet's activity log
173 @return multimap of ordered transactions and accounting entries
174 @warning Returned pointers are *only* valid within the scope of passed acentries
176 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
179 bool AddToWallet(const CWalletTx& wtxIn);
180 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
181 bool EraseFromWallet(uint256 hash);
182 void WalletUpdateSpent(const CTransaction& prevout);
183 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
184 int ScanForWalletTransaction(const uint256& hashTx);
185 void ReacceptWalletTransactions();
186 void ResendWalletTransactions();
187 int64 GetBalance() const;
188 int64 GetUnconfirmedBalance() const;
189 int64 GetImmatureBalance() const;
190 int64 GetStake() const;
191 int64 GetNewMint() const;
192 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
193 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
194 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
196 uint64 GetStakeMintPower(const CKeyStore& keystore, enum StakeWeightMode mode=STAKE_NORMAL);
197 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew);
199 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
200 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
204 int64 AddReserveKey(const CKeyPool& keypool);
205 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
206 void KeepKey(int64 nIndex);
207 void ReturnKey(int64 nIndex);
208 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
209 int64 GetOldestKeyPoolTime();
210 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
212 std::set< std::set<CTxDestination> > GetAddressGroupings();
213 std::map<CTxDestination, int64> GetAddressBalances();
215 bool IsMine(const CTxIn& txin) const;
216 int64 GetDebit(const CTxIn& txin) const;
217 bool IsMine(const CTxOut& txout) const
219 return ::IsMine(*this, txout.scriptPubKey);
221 int64 GetCredit(const CTxOut& txout) const
223 if (!MoneyRange(txout.nValue))
224 throw std::runtime_error("CWallet::GetCredit() : value out of range");
225 return (IsMine(txout) ? txout.nValue : 0);
227 bool IsChange(const CTxOut& txout) const;
228 int64 GetChange(const CTxOut& txout) const
230 if (!MoneyRange(txout.nValue))
231 throw std::runtime_error("CWallet::GetChange() : value out of range");
232 return (IsChange(txout) ? txout.nValue : 0);
234 bool IsMine(const CTransaction& tx) const
236 BOOST_FOREACH(const CTxOut& txout, tx.vout)
241 bool IsFromMe(const CTransaction& tx) const
243 return (GetDebit(tx) > 0);
245 int64 GetDebit(const CTransaction& tx) const
248 BOOST_FOREACH(const CTxIn& txin, tx.vin)
250 nDebit += GetDebit(txin);
251 if (!MoneyRange(nDebit))
252 throw std::runtime_error("CWallet::GetDebit() : value out of range");
256 int64 GetCredit(const CTransaction& tx) const
259 BOOST_FOREACH(const CTxOut& txout, tx.vout)
261 nCredit += GetCredit(txout);
262 if (!MoneyRange(nCredit))
263 throw std::runtime_error("CWallet::GetCredit() : value out of range");
267 int64 GetChange(const CTransaction& tx) const
270 BOOST_FOREACH(const CTxOut& txout, tx.vout)
272 nChange += GetChange(txout);
273 if (!MoneyRange(nChange))
274 throw std::runtime_error("CWallet::GetChange() : value out of range");
278 void SetBestChain(const CBlockLocator& loc);
280 DBErrors LoadWallet(bool& fFirstRunRet);
282 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
284 bool DelAddressBookName(const CTxDestination& address);
286 void UpdatedTransaction(const uint256 &hashTx);
288 void PrintWallet(const CBlock& block);
290 void Inventory(const uint256 &hash)
294 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
295 if (mi != mapRequestCount.end())
302 return setKeyPool.size();
305 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
307 bool SetDefaultKey(const CPubKey &vchPubKey);
309 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
310 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
312 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
313 bool SetMaxVersion(int nVersion);
315 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
316 int GetVersion() { return nWalletVersion; }
318 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
319 void DisableTransaction(const CTransaction &tx);
321 /** Address book entry changed.
322 * @note called with lock cs_wallet held.
324 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
326 /** Wallet transaction added, removed or updated.
327 * @note called with lock cs_wallet held.
329 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
332 /** A key allocated from the key pool. */
340 CReserveKey(CWallet* pwalletIn)
353 CPubKey GetReservedKey();
358 typedef std::map<std::string, std::string> mapValue_t;
361 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
363 if (!mapValue.count("n"))
365 nOrderPos = -1; // TODO: calculate elsewhere
368 nOrderPos = atoi64(mapValue["n"].c_str());
372 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
376 mapValue["n"] = i64tostr(nOrderPos);
380 /** A transaction with a bunch of additional info that only the owner cares about.
381 * It includes any unrecorded transactions needed to link it back to the block chain.
383 class CWalletTx : public CMerkleTx
386 const CWallet* pwallet;
389 std::vector<CMerkleTx> vtxPrev;
391 std::vector<std::pair<std::string, std::string> > vOrderForm;
392 unsigned int fTimeReceivedIsTxTime;
393 unsigned int nTimeReceived; // time received by this node
394 unsigned int nTimeSmart;
396 std::string strFromAccount;
397 std::vector<char> vfSpent; // which outputs are already spent
398 int64 nOrderPos; // position in ordered transaction list
401 mutable bool fDebitCached;
402 mutable bool fCreditCached;
403 mutable bool fAvailableCreditCached;
404 mutable bool fChangeCached;
405 mutable int64 nDebitCached;
406 mutable int64 nCreditCached;
407 mutable int64 nAvailableCreditCached;
408 mutable int64 nChangeCached;
415 CWalletTx(const CWallet* pwalletIn)
420 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
425 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
430 void Init(const CWallet* pwalletIn)
436 fTimeReceivedIsTxTime = false;
440 strFromAccount.clear();
442 fDebitCached = false;
443 fCreditCached = false;
444 fAvailableCreditCached = false;
445 fChangeCached = false;
448 nAvailableCreditCached = 0;
455 CWalletTx* pthis = const_cast<CWalletTx*>(this);
462 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
465 BOOST_FOREACH(char f, vfSpent)
467 str += (f ? '1' : '0');
471 pthis->mapValue["spent"] = str;
473 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
476 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
479 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
482 READWRITE(vOrderForm);
483 READWRITE(fTimeReceivedIsTxTime);
484 READWRITE(nTimeReceived);
490 pthis->strFromAccount = pthis->mapValue["fromaccount"];
492 if (mapValue.count("spent"))
493 BOOST_FOREACH(char c, pthis->mapValue["spent"])
494 pthis->vfSpent.push_back(c != '0');
496 pthis->vfSpent.assign(vout.size(), fSpent);
498 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
500 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
503 pthis->mapValue.erase("fromaccount");
504 pthis->mapValue.erase("version");
505 pthis->mapValue.erase("spent");
506 pthis->mapValue.erase("n");
507 pthis->mapValue.erase("timesmart");
510 // marks certain txout's as spent
511 // returns true if any update took place
512 bool UpdateSpent(const std::vector<char>& vfNewSpent)
514 bool fReturn = false;
515 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
517 if (i == vfSpent.size())
520 if (vfNewSpent[i] && !vfSpent[i])
524 fAvailableCreditCached = false;
530 // make sure balances are recalculated
533 fCreditCached = false;
534 fAvailableCreditCached = false;
535 fDebitCached = false;
536 fChangeCached = false;
539 void BindWallet(CWallet *pwalletIn)
545 void MarkSpent(unsigned int nOut)
547 if (nOut >= vout.size())
548 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
549 vfSpent.resize(vout.size());
552 vfSpent[nOut] = true;
553 fAvailableCreditCached = false;
557 void MarkUnspent(unsigned int nOut)
559 if (nOut >= vout.size())
560 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
561 vfSpent.resize(vout.size());
564 vfSpent[nOut] = false;
565 fAvailableCreditCached = false;
569 bool IsSpent(unsigned int nOut) const
571 if (nOut >= vout.size())
572 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
573 if (nOut >= vfSpent.size())
575 return (!!vfSpent[nOut]);
578 int64 GetDebit() const
584 nDebitCached = pwallet->GetDebit(*this);
589 int64 GetCredit(bool fUseCache=true) const
591 // Must wait until coinbase is safely deep enough in the chain before valuing it
592 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
595 // GetBalance can assume transactions in mapWallet won't change
596 if (fUseCache && fCreditCached)
597 return nCreditCached;
598 nCreditCached = pwallet->GetCredit(*this);
599 fCreditCached = true;
600 return nCreditCached;
603 int64 GetAvailableCredit(bool fUseCache=true) const
605 // Must wait until coinbase is safely deep enough in the chain before valuing it
606 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
609 if (fUseCache && fAvailableCreditCached)
610 return nAvailableCreditCached;
613 for (unsigned int i = 0; i < vout.size(); i++)
617 const CTxOut &txout = vout[i];
618 nCredit += pwallet->GetCredit(txout);
619 if (!MoneyRange(nCredit))
620 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
624 nAvailableCreditCached = nCredit;
625 fAvailableCreditCached = true;
630 int64 GetChange() const
633 return nChangeCached;
634 nChangeCached = pwallet->GetChange(*this);
635 fChangeCached = true;
636 return nChangeCached;
639 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
640 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
642 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
643 int64& nSent, int64& nFee) const;
645 bool IsFromMe() const
647 return (GetDebit() > 0);
650 bool IsConfirmed() const
652 // Quick answer in most cases
655 if (GetDepthInMainChain() >= 1)
657 if (!IsFromMe()) // using wtx's cached debit
660 // If no confirmations but it's from us, we can still
661 // consider it confirmed if all dependencies are confirmed
662 std::map<uint256, const CMerkleTx*> mapPrev;
663 std::vector<const CMerkleTx*> vWorkQueue;
664 vWorkQueue.reserve(vtxPrev.size()+1);
665 vWorkQueue.push_back(this);
666 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
668 const CMerkleTx* ptx = vWorkQueue[i];
672 if (ptx->GetDepthInMainChain() >= 1)
674 if (!pwallet->IsFromMe(*ptx))
679 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
680 mapPrev[tx.GetHash()] = &tx;
683 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
685 if (!mapPrev.count(txin.prevout.hash))
687 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
695 int64 GetTxTime() const;
696 int GetRequestCount() const;
698 void AddSupportingTransactions(CTxDB& txdb);
700 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
701 bool AcceptWalletTransaction();
703 void RelayWalletTransaction(CTxDB& txdb);
704 void RelayWalletTransaction();
717 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
719 tx = txIn; i = iIn; nDepth = nDepthIn;
722 std::string ToString() const
724 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
729 printf("%s\n", ToString().c_str());
736 /** Private key that includes an expiration date in case it never gets used. */
743 std::string strComment;
744 //// todo: add something to note what created it (user, getnewaddress, change)
745 //// maybe should have a map<string, string> property map
747 CWalletKey(int64 nExpires=0)
749 nTimeCreated = (nExpires ? GetTime() : 0);
750 nTimeExpires = nExpires;
755 if (!(nType & SER_GETHASH))
757 READWRITE(vchPrivKey);
758 READWRITE(nTimeCreated);
759 READWRITE(nTimeExpires);
760 READWRITE(strComment);
769 /** Account information.
770 * Stored in wallet with key "acc"+string account name.
784 vchPubKey = CPubKey();
789 if (!(nType & SER_GETHASH))
791 READWRITE(vchPubKey);
797 /** Internal transfers.
798 * Database key is acentry<account><counter>.
800 class CAccountingEntry
803 std::string strAccount;
806 std::string strOtherAccount;
807 std::string strComment;
809 int64 nOrderPos; // position in ordered transaction list
822 strOtherAccount.clear();
829 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
830 if (!(nType & SER_GETHASH))
832 // Note: strAccount is serialized as part of the key, not here.
833 READWRITE(nCreditDebit);
835 READWRITE(strOtherAccount);
839 WriteOrderPos(nOrderPos, me.mapValue);
841 if (!(mapValue.empty() && _ssExtra.empty()))
843 CDataStream ss(nType, nVersion);
844 ss.insert(ss.begin(), '\0');
846 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
847 me.strComment.append(ss.str());
851 READWRITE(strComment);
853 size_t nSepPos = strComment.find("\0", 0, 1);
857 if (std::string::npos != nSepPos)
859 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
861 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
863 ReadOrderPos(me.nOrderPos, me.mapValue);
865 if (std::string::npos != nSepPos)
866 me.strComment.erase(nSepPos);
868 me.mapValue.erase("n");
872 std::vector<char> _ssExtra;
875 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);