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"
22 extern unsigned int nStakeMaxAge;
23 extern bool fWalletUnlockMintOnly;
24 extern bool fConfChange;
25 class CAccountingEntry;
31 // Set of selected transactions
32 typedef std::set<std::pair<const CWalletTx*,unsigned int> > CoinsSet;
34 /** (client) version numbers for particular wallet features */
37 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
39 FEATURE_WALLETCRYPT = 40000, // wallet encryption
40 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
41 FEATURE_MALLKEY = 60017,
42 FEATURE_LATEST = 60017
45 /** A key pool entry */
57 CKeyPool(const CPubKey& vchPubKeyIn)
60 vchPubKey = vchPubKeyIn;
65 if (!(nType & SER_GETHASH))
72 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
73 * and provides the ability to create new transactions.
75 class CWallet : public CCryptoKeyStore
78 bool SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl *coinControl=NULL) const;
80 CWalletDB *pwalletdbEncryption, *pwalletdbDecryption;
82 // the current wallet version: clients below this version are not able to load the wallet
85 // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
86 int nWalletMaxVersion;
88 // stake mining statistics
89 uint64_t nKernelsTried;
90 uint64_t nCoinDaysTried;
93 mutable CCriticalSection cs_wallet;
96 std::string strWalletFile;
98 std::set<int64_t> setKeyPool;
100 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
101 std::map<CMalleableKeyView, CKeyMetadata> mapMalleableKeyMetadata;
104 std::map<CBitcoinAddress, CKeyMetadata> mapKeyMetadata;
106 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
107 MasterKeyMap mapMasterKeys;
108 unsigned int nMasterKeyMaxID;
114 CWallet(std::string strWalletFileIn)
118 strWalletFile = strWalletFileIn;
123 nWalletVersion = FEATURE_BASE;
124 nWalletMaxVersion = FEATURE_BASE;
127 pwalletdbEncryption = NULL;
128 pwalletdbDecryption = NULL;
135 std::map<uint256, CWalletTx> mapWallet;
136 std::vector<uint256> vMintingWalletUpdated;
137 int64_t nOrderPosNext;
138 std::map<uint256, int> mapRequestCount;
140 std::map<CBitcoinAddress, std::string> mapAddressBook;
142 CPubKey vchDefaultKey;
143 int64_t nTimeFirstKey;
145 // check whether we are allowed to upgrade (or already support) to the named feature
146 bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
148 void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const;
149 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
150 bool SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
152 // Simple select (without randomization)
153 bool SelectCoinsSimple(int64_t nTargetValue, int64_t nMinValue, int64_t nMaxValue, unsigned int nSpendTime, int nMinConf, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
155 // keystore implementation
156 // Generate a new key
157 CPubKey GenerateNewKey();
158 CMalleableKeyView GenerateNewMalleableKey();
159 // Adds a key to the store, and saves it to disk.
160 bool AddKey(const CKey& key);
161 bool AddKey(const CMalleableKey& mKey);
162 // Adds a key to the store, without saving it to disk (used by LoadWallet)
163 bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
164 // Load metadata (used by LoadWallet)
165 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
166 bool LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata);
168 // Load malleable key without saving it to disk (used by LoadWallet)
169 bool LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH) { return CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH); }
170 bool LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH) { return CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH); }
172 bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
174 // Adds an encrypted key to the store, and saves it to disk.
175 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
176 bool AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH);
177 // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
178 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
179 bool AddCScript(const CScript& redeemScript);
180 bool LoadCScript(const CScript& redeemScript);
182 // Adds a watch-only address to the store, and saves it to disk.
183 bool AddWatchOnly(const CScript &dest);
184 bool RemoveWatchOnly(const CScript &dest);
185 // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
186 bool LoadWatchOnly(const CScript &dest);
188 bool Unlock(const SecureString& strWalletPassphrase);
189 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
190 bool EncryptWallet(const SecureString& strWalletPassphrase);
191 bool DecryptWallet(const SecureString& strWalletPassphrase);
193 void GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const;
196 /** Increment the next transaction order id
197 @return next transaction order id
199 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
201 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
202 typedef std::multimap<int64_t, TxPair > TxItems;
204 /** Get the wallet's activity log
205 @return multimap of ordered transactions and accounting entries
206 @warning Returned pointers are *only* valid within the scope of passed acentries
208 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
211 bool AddToWallet(const CWalletTx& wtxIn);
212 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
213 bool EraseFromWallet(uint256 hash);
215 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
216 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
217 int ScanForWalletTransaction(const uint256& hashTx);
218 void ReacceptWalletTransactions();
219 void ResendWalletTransactions(bool fForceResend=false);
220 int64_t GetBalance() const;
221 int64_t GetWatchOnlyBalance() const;
222 int64_t GetUnconfirmedBalance() const;
223 int64_t GetUnconfirmedWatchOnlyBalance() const;
224 int64_t GetImmatureBalance() const;
225 int64_t GetImmatureWatchOnlyBalance() const;
226 int64_t GetStake() const;
227 int64_t GetNewMint() const;
228 int64_t GetWatchOnlyStake() const;
229 int64_t GetWatchOnlyNewMint() const;
230 bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
231 bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
232 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
234 void GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight);
235 bool CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nTime, uint32_t nBits, CTransaction &txNew, CKey& key);
236 bool MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nMaxValue, std::list<uint256>& listMerged);
238 std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
240 bool NewKeyPool(unsigned int nSize = 0);
241 bool TopUpKeyPool(unsigned int nSize = 0);
242 int64_t AddReserveKey(const CKeyPool& keypool);
243 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
244 void KeepKey(int64_t nIndex);
245 void ReturnKey(int64_t nIndex);
246 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
247 int64_t GetOldestKeyPoolTime();
248 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
250 std::set< std::set<CBitcoinAddress> > GetAddressGroupings();
251 std::map<CBitcoinAddress, int64_t> GetAddressBalances();
253 isminetype IsMine(const CTxIn& txin) const;
254 int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
255 isminetype IsMine(const CTxOut& txout) const
257 return ::IsMine(*this, txout.scriptPubKey);
259 int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const
261 if (!MoneyRange(txout.nValue))
262 throw std::runtime_error("CWallet::GetCredit() : value out of range");
263 return (IsMine(txout) & filter ? txout.nValue : 0);
265 bool IsChange(const CTxOut& txout) const;
266 int64_t GetChange(const CTxOut& txout) const
268 if (!MoneyRange(txout.nValue))
269 throw std::runtime_error("CWallet::GetChange() : value out of range");
270 return (IsChange(txout) ? txout.nValue : 0);
272 bool IsMine(const CTransaction& tx) const
274 BOOST_FOREACH(const CTxOut& txout, tx.vout)
275 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
279 bool IsFromMe(const CTransaction& tx) const
281 return (GetDebit(tx, MINE_ALL) > 0);
283 int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const
286 BOOST_FOREACH(const CTxIn& txin, tx.vin)
288 nDebit += GetDebit(txin, filter);
289 if (!MoneyRange(nDebit))
290 throw std::runtime_error("CWallet::GetDebit() : value out of range");
294 int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const
297 BOOST_FOREACH(const CTxOut& txout, tx.vout)
299 nCredit += GetCredit(txout, filter);
300 if (!MoneyRange(nCredit))
301 throw std::runtime_error("CWallet::GetCredit() : value out of range");
305 int64_t GetChange(const CTransaction& tx) const
308 BOOST_FOREACH(const CTxOut& txout, tx.vout)
310 nChange += GetChange(txout);
311 if (!MoneyRange(nChange))
312 throw std::runtime_error("CWallet::GetChange() : value out of range");
316 void SetBestChain(const CBlockLocator& loc);
318 DBErrors LoadWallet(bool& fFirstRunRet);
320 DBErrors ZapWalletTx();
322 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
324 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
326 bool DelAddressBookName(const CBitcoinAddress& address);
328 void UpdatedTransaction(const uint256 &hashTx);
330 void PrintWallet(const CBlock& block);
332 void Inventory(const uint256 &hash)
336 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
337 if (mi != mapRequestCount.end())
342 unsigned int GetKeyPoolSize()
344 return (unsigned int)(setKeyPool.size());
347 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
349 bool SetDefaultKey(const CPubKey &vchPubKey);
351 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
352 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
354 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
355 bool SetMaxVersion(int nVersion);
357 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
358 int GetVersion() { return nWalletVersion; }
360 void FixSpentCoins(int& nMismatchSpent, int64_t& nBalanceInQuestion, bool fCheckOnly = false);
361 void DisableTransaction(const CTransaction &tx);
363 /** Address book entry changed.
364 * @note called with lock cs_wallet held.
366 boost::signals2::signal<void (CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
368 /** Wallet transaction added, removed or updated.
369 * @note called with lock cs_wallet held.
371 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
373 /** Watch-only address added */
374 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
377 /** A key allocated from the key pool. */
385 CReserveKey(CWallet* pwalletIn)
398 CPubKey GetReservedKey();
403 typedef std::map<std::string, std::string> mapValue_t;
406 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
408 if (!mapValue.count("n"))
410 nOrderPos = -1; // TODO: calculate elsewhere
413 nOrderPos = atoi64(mapValue["n"].c_str());
417 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
421 mapValue["n"] = i64tostr(nOrderPos);
425 /** A transaction with a bunch of additional info that only the owner cares about.
426 * It includes any unrecorded transactions needed to link it back to the block chain.
428 class CWalletTx : public CMerkleTx
431 const CWallet* pwallet;
434 std::vector<CMerkleTx> vtxPrev;
436 std::vector<std::pair<std::string, std::string> > vOrderForm;
437 unsigned int fTimeReceivedIsTxTime;
438 unsigned int nTimeReceived; // time received by this node
439 unsigned int nTimeSmart;
441 std::string strFromAccount;
442 std::vector<char> vfSpent; // which outputs are already spent
443 int64_t nOrderPos; // position in ordered transaction list
446 mutable bool fDebitCached;
447 mutable bool fWatchDebitCached;
448 mutable bool fCreditCached;
449 mutable bool fWatchCreditCached;
450 mutable bool fAvailableCreditCached;
451 mutable bool fImmatureCreditCached;
452 mutable bool fImmatureWatchCreditCached;
453 mutable bool fAvailableWatchCreditCached;
454 mutable bool fChangeCached;
455 mutable int64_t nDebitCached;
456 mutable int64_t nWatchDebitCached;
457 mutable int64_t nCreditCached;
458 mutable int64_t nWatchCreditCached;
459 mutable int64_t nAvailableCreditCached;
460 mutable int64_t nImmatureCreditCached;
461 mutable int64_t nImmatureWatchCreditCached;
462 mutable int64_t nAvailableWatchCreditCached;
463 mutable int64_t nChangeCached;
470 CWalletTx(const CWallet* pwalletIn)
475 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
480 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
485 void Init(const CWallet* pwalletIn)
491 fTimeReceivedIsTxTime = false;
495 strFromAccount.clear();
497 fDebitCached = false;
498 fWatchDebitCached = false;
499 fCreditCached = false;
500 fWatchCreditCached = false;
501 fAvailableCreditCached = false;
502 fAvailableWatchCreditCached = false;
503 fImmatureCreditCached = false;
504 fImmatureWatchCreditCached = false;
505 fChangeCached = false;
507 nWatchDebitCached = 0;
509 nWatchCreditCached = 0;
510 nAvailableCreditCached = 0;
511 nAvailableWatchCreditCached = 0;
512 nImmatureCreditCached = 0;
513 nImmatureWatchCreditCached = 0;
520 CWalletTx* pthis = const_cast<CWalletTx*>(this);
527 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
530 BOOST_FOREACH(char f, vfSpent)
532 str += (f ? '1' : '0');
536 pthis->mapValue["spent"] = str;
538 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
541 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
544 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
547 READWRITE(vOrderForm);
548 READWRITE(fTimeReceivedIsTxTime);
549 READWRITE(nTimeReceived);
555 pthis->strFromAccount = pthis->mapValue["fromaccount"];
557 if (mapValue.count("spent"))
558 BOOST_FOREACH(char c, pthis->mapValue["spent"])
559 pthis->vfSpent.push_back(c != '0');
561 pthis->vfSpent.assign(vout.size(), fSpent);
563 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
565 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
568 pthis->mapValue.erase("fromaccount");
569 pthis->mapValue.erase("version");
570 pthis->mapValue.erase("spent");
571 pthis->mapValue.erase("n");
572 pthis->mapValue.erase("timesmart");
575 // marks certain txout's as spent
576 // returns true if any update took place
577 bool UpdateSpent(const std::vector<char>& vfNewSpent)
579 bool fReturn = false;
580 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
582 if (i == vfSpent.size())
585 if (vfNewSpent[i] && !vfSpent[i])
589 fAvailableCreditCached = fAvailableWatchCreditCached = false;
595 // make sure balances are recalculated
598 fCreditCached = false;
599 fAvailableCreditCached = fAvailableWatchCreditCached = false;
600 fDebitCached = fWatchDebitCached = false;
601 fChangeCached = false;
604 void BindWallet(CWallet *pwalletIn)
610 void MarkSpent(unsigned int nOut)
612 if (nOut >= vout.size())
613 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
614 vfSpent.resize(vout.size());
617 vfSpent[nOut] = true;
618 fAvailableCreditCached = fAvailableWatchCreditCached = false;
622 void MarkUnspent(unsigned int nOut)
624 if (nOut >= vout.size())
625 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
626 vfSpent.resize(vout.size());
629 vfSpent[nOut] = false;
630 fAvailableCreditCached = fAvailableWatchCreditCached = false;
634 bool IsSpent(unsigned int nOut) const
636 if (nOut >= vout.size())
637 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
638 if (nOut >= vfSpent.size())
640 return (!!vfSpent[nOut]);
643 int64_t GetDebit(const isminefilter& filter) const
649 if (filter & MINE_SPENDABLE)
652 nDebit += nDebitCached;
655 nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
657 nDebit += nDebitCached;
660 if (filter & MINE_WATCH_ONLY)
662 if (fWatchDebitCached)
663 nDebit += nWatchDebitCached;
666 nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
667 fWatchDebitCached = true;
668 nDebit += nWatchDebitCached;
675 int64_t GetCredit(const isminefilter& filter) const
677 // Must wait until coinbase is safely deep enough in the chain before valuing it
678 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
682 if (filter & MINE_SPENDABLE)
684 // GetBalance can assume transactions in mapWallet won't change
686 credit += nCreditCached;
689 nCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
690 fCreditCached = true;
691 credit += nCreditCached;
694 if (filter & MINE_WATCH_ONLY)
696 if (fWatchCreditCached)
697 credit += nWatchCreditCached;
700 nWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
701 fWatchCreditCached = true;
702 credit += nWatchCreditCached;
708 int64_t GetImmatureCredit(bool fUseCache=true) const
710 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
712 if (fUseCache && fImmatureCreditCached)
713 return nImmatureCreditCached;
714 nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
715 fImmatureCreditCached = true;
716 return nImmatureCreditCached;
722 int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const
724 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
726 if (fUseCache && fImmatureWatchCreditCached)
727 return nImmatureWatchCreditCached;
728 nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
729 fImmatureWatchCreditCached = true;
730 return nImmatureWatchCreditCached;
737 int64_t GetAvailableCredit(bool fUseCache=true) const
739 // Must wait until coinbase is safely deep enough in the chain before valuing it
740 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
744 if (fAvailableCreditCached)
745 return nAvailableCreditCached;
749 for (unsigned int i = 0; i < vout.size(); i++)
753 const CTxOut &txout = vout[i];
754 nCredit += pwallet->GetCredit(txout, MINE_SPENDABLE);
755 if (!MoneyRange(nCredit))
756 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
760 nAvailableCreditCached = nCredit;
761 fAvailableCreditCached = true;
766 int64_t GetAvailableWatchCredit(bool fUseCache=true) const
768 // Must wait until coinbase is safely deep enough in the chain before valuing it
769 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
773 if (fAvailableWatchCreditCached)
774 return nAvailableWatchCreditCached;
778 for (unsigned int i = 0; i < vout.size(); i++)
782 const CTxOut &txout = vout[i];
783 nCredit += pwallet->GetCredit(txout, MINE_WATCH_ONLY);
784 if (!MoneyRange(nCredit))
785 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
789 nAvailableWatchCreditCached = nCredit;
790 fAvailableWatchCreditCached = true;
795 int64_t GetChange() const
798 return nChangeCached;
799 nChangeCached = pwallet->GetChange(*this);
800 fChangeCached = true;
801 return nChangeCached;
804 void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
805 std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
807 void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
808 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
810 bool IsFromMe(const isminefilter& filter) const
812 return (GetDebit(filter) > 0);
815 bool IsTrusted() const
817 // Quick answer in most cases
820 if (GetDepthInMainChain() >= 1)
822 if (fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
825 // If no confirmations but it's from us, we can still
826 // consider it confirmed if all dependencies are confirmed
827 std::map<uint256, const CMerkleTx*> mapPrev;
828 std::vector<const CMerkleTx*> vWorkQueue;
829 vWorkQueue.reserve(vtxPrev.size()+1);
830 vWorkQueue.push_back(this);
831 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
833 const CMerkleTx* ptx = vWorkQueue[i];
837 if (ptx->GetDepthInMainChain() >= 1)
839 if (!pwallet->IsFromMe(*ptx))
844 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
845 mapPrev[tx.GetHash()] = &tx;
848 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
850 if (!mapPrev.count(txin.prevout.hash))
852 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
861 int64_t GetTxTime() const;
862 int GetRequestCount() const;
864 void AddSupportingTransactions(CTxDB& txdb);
866 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
867 bool AcceptWalletTransaction();
869 void RelayWalletTransaction(CTxDB& txdb);
870 void RelayWalletTransaction();
884 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
886 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
889 std::string ToString() const
891 return strprintf("COutput(%s, %d, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, fSpendable, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
896 printf("%s\n", ToString().c_str());
903 /** Private key that includes an expiration date in case it never gets used. */
908 int64_t nTimeCreated;
909 int64_t nTimeExpires;
910 std::string strComment;
911 //// todo: add something to note what created it (user, getnewaddress, change)
912 //// maybe should have a map<string, string> property map
914 CWalletKey(int64_t nExpires=0)
916 nTimeCreated = (nExpires ? GetTime() : 0);
917 nTimeExpires = nExpires;
922 if (!(nType & SER_GETHASH))
924 READWRITE(vchPrivKey);
925 READWRITE(nTimeCreated);
926 READWRITE(nTimeExpires);
927 READWRITE(strComment);
936 /** Account information.
937 * Stored in wallet with key "acc"+string account name.
951 vchPubKey = CPubKey();
956 if (!(nType & SER_GETHASH))
958 READWRITE(vchPubKey);
964 /** Internal transfers.
965 * Database key is acentry<account><counter>.
967 class CAccountingEntry
970 std::string strAccount;
971 int64_t nCreditDebit;
973 std::string strOtherAccount;
974 std::string strComment;
976 int64_t nOrderPos; // position in ordered transaction list
989 strOtherAccount.clear();
996 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
997 if (!(nType & SER_GETHASH))
999 // Note: strAccount is serialized as part of the key, not here.
1000 READWRITE(nCreditDebit);
1002 READWRITE(strOtherAccount);
1006 WriteOrderPos(nOrderPos, me.mapValue);
1008 if (!(mapValue.empty() && _ssExtra.empty()))
1010 CDataStream ss(nType, nVersion);
1011 ss.insert(ss.begin(), '\0');
1013 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
1014 me.strComment.append(ss.str());
1018 READWRITE(strComment);
1020 size_t nSepPos = strComment.find("\0", 0, 1);
1023 me.mapValue.clear();
1024 if (std::string::npos != nSepPos)
1026 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
1028 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
1030 ReadOrderPos(me.nOrderPos, me.mapValue);
1032 if (std::string::npos != nSepPos)
1033 me.strComment.erase(nSepPos);
1035 me.mapValue.erase("n");
1039 std::vector<char> _ssExtra;
1042 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);