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;
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;
131 // check whether we are allowed to upgrade (or already support) to the named feature
132 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
134 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true) const;
135 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;
136 // keystore implementation
137 // Generate a new key
138 CPubKey GenerateNewKey();
139 // Adds a key to the store, and saves it to disk.
140 bool AddKey(const CKey& key);
141 // Adds a key to the store, without saving it to disk (used by LoadWallet)
142 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
144 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
146 // Adds an encrypted key to the store, and saves it to disk.
147 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
148 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
149 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
150 bool AddCScript(const CScript& redeemScript);
151 bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
153 bool Unlock(const SecureString& strWalletPassphrase);
154 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
155 bool EncryptWallet(const SecureString& strWalletPassphrase);
157 /** Increment the next transaction order id
158 @return next transaction order id
160 int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
162 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
163 typedef std::multimap<int64, TxPair > TxItems;
165 /** Get the wallet's activity log
166 @return multimap of ordered transactions and accounting entries
167 @warning Returned pointers are *only* valid within the scope of passed acentries
169 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
172 bool AddToWallet(const CWalletTx& wtxIn);
173 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
174 bool EraseFromWallet(uint256 hash);
175 void WalletUpdateSpent(const CTransaction& prevout);
176 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
177 int ScanForWalletTransaction(const uint256& hashTx);
178 void ReacceptWalletTransactions();
179 void ResendWalletTransactions();
180 int64 GetBalance() const;
181 int64 GetUnconfirmedBalance() const;
182 int64 GetImmatureBalance() const;
183 int64 GetStake() const;
184 int64 GetNewMint() const;
185 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
186 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
187 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
189 uint64 GetStakeMintPower(const CKeyStore& keystore, enum StakeWeightMode mode=STAKE_NORMAL);
190 bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew);
192 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
193 std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
197 int64 AddReserveKey(const CKeyPool& keypool);
198 void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
199 void KeepKey(int64 nIndex);
200 void ReturnKey(int64 nIndex);
201 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
202 int64 GetOldestKeyPoolTime();
203 void GetAllReserveKeys(std::set<CKeyID>& setAddress);
205 std::set< std::set<CTxDestination> > GetAddressGroupings();
206 std::map<CTxDestination, int64> GetAddressBalances();
208 bool IsMine(const CTxIn& txin) const;
209 int64 GetDebit(const CTxIn& txin) const;
210 bool IsMine(const CTxOut& txout) const
212 return ::IsMine(*this, txout.scriptPubKey);
214 int64 GetCredit(const CTxOut& txout) const
216 if (!MoneyRange(txout.nValue))
217 throw std::runtime_error("CWallet::GetCredit() : value out of range");
218 return (IsMine(txout) ? txout.nValue : 0);
220 bool IsChange(const CTxOut& txout) const;
221 int64 GetChange(const CTxOut& txout) const
223 if (!MoneyRange(txout.nValue))
224 throw std::runtime_error("CWallet::GetChange() : value out of range");
225 return (IsChange(txout) ? txout.nValue : 0);
227 bool IsMine(const CTransaction& tx) const
229 BOOST_FOREACH(const CTxOut& txout, tx.vout)
234 bool IsFromMe(const CTransaction& tx) const
236 return (GetDebit(tx) > 0);
238 int64 GetDebit(const CTransaction& tx) const
241 BOOST_FOREACH(const CTxIn& txin, tx.vin)
243 nDebit += GetDebit(txin);
244 if (!MoneyRange(nDebit))
245 throw std::runtime_error("CWallet::GetDebit() : value out of range");
249 int64 GetCredit(const CTransaction& tx) const
252 BOOST_FOREACH(const CTxOut& txout, tx.vout)
254 nCredit += GetCredit(txout);
255 if (!MoneyRange(nCredit))
256 throw std::runtime_error("CWallet::GetCredit() : value out of range");
260 int64 GetChange(const CTransaction& tx) const
263 BOOST_FOREACH(const CTxOut& txout, tx.vout)
265 nChange += GetChange(txout);
266 if (!MoneyRange(nChange))
267 throw std::runtime_error("CWallet::GetChange() : value out of range");
271 void SetBestChain(const CBlockLocator& loc);
273 DBErrors LoadWallet(bool& fFirstRunRet);
275 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
277 bool DelAddressBookName(const CTxDestination& address);
279 void UpdatedTransaction(const uint256 &hashTx);
281 void PrintWallet(const CBlock& block);
283 void Inventory(const uint256 &hash)
287 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
288 if (mi != mapRequestCount.end())
295 return setKeyPool.size();
298 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
300 bool SetDefaultKey(const CPubKey &vchPubKey);
302 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
303 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
305 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
306 bool SetMaxVersion(int nVersion);
308 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
309 int GetVersion() { return nWalletVersion; }
311 void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
312 void DisableTransaction(const CTransaction &tx);
314 /** Address book entry changed.
315 * @note called with lock cs_wallet held.
317 boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
319 /** Wallet transaction added, removed or updated.
320 * @note called with lock cs_wallet held.
322 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
325 /** A key allocated from the key pool. */
333 CReserveKey(CWallet* pwalletIn)
346 CPubKey GetReservedKey();
351 typedef std::map<std::string, std::string> mapValue_t;
354 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
356 if (!mapValue.count("n"))
358 nOrderPos = -1; // TODO: calculate elsewhere
361 nOrderPos = atoi64(mapValue["n"].c_str());
365 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
369 mapValue["n"] = i64tostr(nOrderPos);
373 /** A transaction with a bunch of additional info that only the owner cares about.
374 * It includes any unrecorded transactions needed to link it back to the block chain.
376 class CWalletTx : public CMerkleTx
379 const CWallet* pwallet;
382 std::vector<CMerkleTx> vtxPrev;
384 std::vector<std::pair<std::string, std::string> > vOrderForm;
385 unsigned int fTimeReceivedIsTxTime;
386 unsigned int nTimeReceived; // time received by this node
387 unsigned int nTimeSmart;
389 std::string strFromAccount;
390 std::vector<char> vfSpent; // which outputs are already spent
391 int64 nOrderPos; // position in ordered transaction list
394 mutable bool fDebitCached;
395 mutable bool fCreditCached;
396 mutable bool fAvailableCreditCached;
397 mutable bool fChangeCached;
398 mutable int64 nDebitCached;
399 mutable int64 nCreditCached;
400 mutable int64 nAvailableCreditCached;
401 mutable int64 nChangeCached;
408 CWalletTx(const CWallet* pwalletIn)
413 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
418 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
423 void Init(const CWallet* pwalletIn)
429 fTimeReceivedIsTxTime = false;
433 strFromAccount.clear();
435 fDebitCached = false;
436 fCreditCached = false;
437 fAvailableCreditCached = false;
438 fChangeCached = false;
441 nAvailableCreditCached = 0;
448 CWalletTx* pthis = const_cast<CWalletTx*>(this);
455 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
458 BOOST_FOREACH(char f, vfSpent)
460 str += (f ? '1' : '0');
464 pthis->mapValue["spent"] = str;
466 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
469 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
472 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
475 READWRITE(vOrderForm);
476 READWRITE(fTimeReceivedIsTxTime);
477 READWRITE(nTimeReceived);
483 pthis->strFromAccount = pthis->mapValue["fromaccount"];
485 if (mapValue.count("spent"))
486 BOOST_FOREACH(char c, pthis->mapValue["spent"])
487 pthis->vfSpent.push_back(c != '0');
489 pthis->vfSpent.assign(vout.size(), fSpent);
491 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
493 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
496 pthis->mapValue.erase("fromaccount");
497 pthis->mapValue.erase("version");
498 pthis->mapValue.erase("spent");
499 pthis->mapValue.erase("n");
500 pthis->mapValue.erase("timesmart");
503 // marks certain txout's as spent
504 // returns true if any update took place
505 bool UpdateSpent(const std::vector<char>& vfNewSpent)
507 bool fReturn = false;
508 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
510 if (i == vfSpent.size())
513 if (vfNewSpent[i] && !vfSpent[i])
517 fAvailableCreditCached = false;
523 // make sure balances are recalculated
526 fCreditCached = false;
527 fAvailableCreditCached = false;
528 fDebitCached = false;
529 fChangeCached = false;
532 void BindWallet(CWallet *pwalletIn)
538 void MarkSpent(unsigned int nOut)
540 if (nOut >= vout.size())
541 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
542 vfSpent.resize(vout.size());
545 vfSpent[nOut] = true;
546 fAvailableCreditCached = false;
550 void MarkUnspent(unsigned int nOut)
552 if (nOut >= vout.size())
553 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
554 vfSpent.resize(vout.size());
557 vfSpent[nOut] = false;
558 fAvailableCreditCached = false;
562 bool IsSpent(unsigned int nOut) const
564 if (nOut >= vout.size())
565 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
566 if (nOut >= vfSpent.size())
568 return (!!vfSpent[nOut]);
571 int64 GetDebit() const
577 nDebitCached = pwallet->GetDebit(*this);
582 int64 GetCredit(bool fUseCache=true) const
584 // Must wait until coinbase is safely deep enough in the chain before valuing it
585 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
588 // GetBalance can assume transactions in mapWallet won't change
589 if (fUseCache && fCreditCached)
590 return nCreditCached;
591 nCreditCached = pwallet->GetCredit(*this);
592 fCreditCached = true;
593 return nCreditCached;
596 int64 GetAvailableCredit(bool fUseCache=true) const
598 // Must wait until coinbase is safely deep enough in the chain before valuing it
599 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
602 if (fUseCache && fAvailableCreditCached)
603 return nAvailableCreditCached;
606 for (unsigned int i = 0; i < vout.size(); i++)
610 const CTxOut &txout = vout[i];
611 nCredit += pwallet->GetCredit(txout);
612 if (!MoneyRange(nCredit))
613 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
617 nAvailableCreditCached = nCredit;
618 fAvailableCreditCached = true;
623 int64 GetChange() const
626 return nChangeCached;
627 nChangeCached = pwallet->GetChange(*this);
628 fChangeCached = true;
629 return nChangeCached;
632 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
633 std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
635 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
636 int64& nSent, int64& nFee) const;
638 bool IsFromMe() const
640 return (GetDebit() > 0);
643 bool IsConfirmed() const
645 // Quick answer in most cases
648 if (GetDepthInMainChain() >= 1)
650 if (!IsFromMe()) // using wtx's cached debit
653 // If no confirmations but it's from us, we can still
654 // consider it confirmed if all dependencies are confirmed
655 std::map<uint256, const CMerkleTx*> mapPrev;
656 std::vector<const CMerkleTx*> vWorkQueue;
657 vWorkQueue.reserve(vtxPrev.size()+1);
658 vWorkQueue.push_back(this);
659 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
661 const CMerkleTx* ptx = vWorkQueue[i];
665 if (ptx->GetDepthInMainChain() >= 1)
667 if (!pwallet->IsFromMe(*ptx))
672 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
673 mapPrev[tx.GetHash()] = &tx;
676 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
678 if (!mapPrev.count(txin.prevout.hash))
680 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
688 int64 GetTxTime() const;
689 int GetRequestCount() const;
691 void AddSupportingTransactions(CTxDB& txdb);
693 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
694 bool AcceptWalletTransaction();
696 void RelayWalletTransaction(CTxDB& txdb);
697 void RelayWalletTransaction();
710 COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
712 tx = txIn; i = iIn; nDepth = nDepthIn;
715 std::string ToString() const
717 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
722 printf("%s\n", ToString().c_str());
729 /** Private key that includes an expiration date in case it never gets used. */
736 std::string strComment;
737 //// todo: add something to note what created it (user, getnewaddress, change)
738 //// maybe should have a map<string, string> property map
740 CWalletKey(int64 nExpires=0)
742 nTimeCreated = (nExpires ? GetTime() : 0);
743 nTimeExpires = nExpires;
748 if (!(nType & SER_GETHASH))
750 READWRITE(vchPrivKey);
751 READWRITE(nTimeCreated);
752 READWRITE(nTimeExpires);
753 READWRITE(strComment);
762 /** Account information.
763 * Stored in wallet with key "acc"+string account name.
777 vchPubKey = CPubKey();
782 if (!(nType & SER_GETHASH))
784 READWRITE(vchPubKey);
790 /** Internal transfers.
791 * Database key is acentry<account><counter>.
793 class CAccountingEntry
796 std::string strAccount;
799 std::string strOtherAccount;
800 std::string strComment;
802 int64 nOrderPos; // position in ordered transaction list
815 strOtherAccount.clear();
822 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
823 if (!(nType & SER_GETHASH))
825 // Note: strAccount is serialized as part of the key, not here.
826 READWRITE(nCreditDebit);
828 READWRITE(strOtherAccount);
832 WriteOrderPos(nOrderPos, me.mapValue);
834 if (!(mapValue.empty() && _ssExtra.empty()))
836 CDataStream ss(nType, nVersion);
837 ss.insert(ss.begin(), '\0');
839 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
840 me.strComment.append(ss.str());
844 READWRITE(strComment);
846 size_t nSepPos = strComment.find("\0", 0, 1);
850 if (std::string::npos != nSepPos)
852 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
854 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
856 ReadOrderPos(me.nOrderPos, me.mapValue);
858 if (std::string::npos != nSepPos)
859 me.strComment.erase(nSepPos);
861 me.mapValue.erase("n");
865 std::vector<char> _ssExtra;
868 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);