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;
194 bool GetPEM(const CKeyID &keyID, const std::string &fileName, const SecureString &strPassPhrase) const;
197 /** Increment the next transaction order id
198 @return next transaction order id
200 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
202 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
203 typedef std::multimap<int64_t, TxPair > TxItems;
205 /** Get the wallet's activity log
206 @return multimap of ordered transactions and accounting entries
207 @warning Returned pointers are *only* valid within the scope of passed acentries
209 TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
212 bool AddToWallet(const CWalletTx& wtxIn);
213 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
214 bool EraseFromWallet(uint256 hash);
216 void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
217 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
218 int ScanForWalletTransaction(const uint256& hashTx);
219 void ReacceptWalletTransactions();
220 void ResendWalletTransactions(bool fForceResend=false);
221 int64_t GetBalance() const;
222 int64_t GetWatchOnlyBalance() const;
223 int64_t GetUnconfirmedBalance() const;
224 int64_t GetUnconfirmedWatchOnlyBalance() const;
225 int64_t GetImmatureBalance() const;
226 int64_t GetImmatureWatchOnlyBalance() const;
227 int64_t GetStake() const;
228 int64_t GetNewMint() const;
229 int64_t GetWatchOnlyStake() const;
230 int64_t GetWatchOnlyNewMint() const;
231 bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
232 bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
233 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
235 void GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight);
236 bool CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nTime, uint32_t nBits, CTransaction &txNew, CKey& key);
237 bool MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nMaxValue, std::list<uint256>& listMerged);
239 std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
241 bool NewKeyPool(unsigned int nSize = 0);
242 bool TopUpKeyPool(unsigned int nSize = 0);
243 int64_t AddReserveKey(const CKeyPool& keypool);
244 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
245 void KeepKey(int64_t nIndex);
246 void ReturnKey(int64_t nIndex);
247 bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
248 int64_t GetOldestKeyPoolTime();
249 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
251 std::set< std::set<CBitcoinAddress> > GetAddressGroupings();
252 std::map<CBitcoinAddress, int64_t> GetAddressBalances();
254 isminetype IsMine(const CTxIn& txin) const;
255 int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
256 isminetype IsMine(const CTxOut& txout) const
258 return ::IsMine(*this, txout.scriptPubKey);
260 int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const
262 if (!MoneyRange(txout.nValue))
263 throw std::runtime_error("CWallet::GetCredit() : value out of range");
264 return (IsMine(txout) & filter ? txout.nValue : 0);
266 bool IsChange(const CTxOut& txout) const;
267 int64_t GetChange(const CTxOut& txout) const
269 if (!MoneyRange(txout.nValue))
270 throw std::runtime_error("CWallet::GetChange() : value out of range");
271 return (IsChange(txout) ? txout.nValue : 0);
273 bool IsMine(const CTransaction& tx) const
275 BOOST_FOREACH(const CTxOut& txout, tx.vout)
276 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
280 bool IsFromMe(const CTransaction& tx) const
282 return (GetDebit(tx, MINE_ALL) > 0);
284 int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const
287 BOOST_FOREACH(const CTxIn& txin, tx.vin)
289 nDebit += GetDebit(txin, filter);
290 if (!MoneyRange(nDebit))
291 throw std::runtime_error("CWallet::GetDebit() : value out of range");
295 int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const
298 BOOST_FOREACH(const CTxOut& txout, tx.vout)
300 nCredit += GetCredit(txout, filter);
301 if (!MoneyRange(nCredit))
302 throw std::runtime_error("CWallet::GetCredit() : value out of range");
306 int64_t GetChange(const CTransaction& tx) const
309 BOOST_FOREACH(const CTxOut& txout, tx.vout)
311 nChange += GetChange(txout);
312 if (!MoneyRange(nChange))
313 throw std::runtime_error("CWallet::GetChange() : value out of range");
317 void SetBestChain(const CBlockLocator& loc);
319 DBErrors LoadWallet(bool& fFirstRunRet);
321 DBErrors ZapWalletTx();
323 bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
325 bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
327 bool DelAddressBookName(const CBitcoinAddress& address);
329 void UpdatedTransaction(const uint256 &hashTx);
331 void PrintWallet(const CBlock& block);
333 void Inventory(const uint256 &hash)
337 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
338 if (mi != mapRequestCount.end())
343 unsigned int GetKeyPoolSize()
345 return (unsigned int)(setKeyPool.size());
348 bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
350 bool SetDefaultKey(const CPubKey &vchPubKey);
352 // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
353 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
355 // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
356 bool SetMaxVersion(int nVersion);
358 // get the current wallet format (the oldest client version guaranteed to understand this wallet)
359 int GetVersion() { return nWalletVersion; }
361 void FixSpentCoins(int& nMismatchSpent, int64_t& nBalanceInQuestion, bool fCheckOnly = false);
362 void DisableTransaction(const CTransaction &tx);
364 /** Address book entry changed.
365 * @note called with lock cs_wallet held.
367 boost::signals2::signal<void (CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
369 /** Wallet transaction added, removed or updated.
370 * @note called with lock cs_wallet held.
372 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
374 /** Watch-only address added */
375 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
378 /** A key allocated from the key pool. */
386 CReserveKey(CWallet* pwalletIn)
399 CPubKey GetReservedKey();
404 typedef std::map<std::string, std::string> mapValue_t;
407 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
409 if (!mapValue.count("n"))
411 nOrderPos = -1; // TODO: calculate elsewhere
414 nOrderPos = atoi64(mapValue["n"].c_str());
418 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
422 mapValue["n"] = i64tostr(nOrderPos);
426 /** A transaction with a bunch of additional info that only the owner cares about.
427 * It includes any unrecorded transactions needed to link it back to the block chain.
429 class CWalletTx : public CMerkleTx
432 const CWallet* pwallet;
435 std::vector<CMerkleTx> vtxPrev;
437 std::vector<std::pair<std::string, std::string> > vOrderForm;
438 unsigned int fTimeReceivedIsTxTime;
439 unsigned int nTimeReceived; // time received by this node
440 unsigned int nTimeSmart;
442 std::string strFromAccount;
443 std::vector<char> vfSpent; // which outputs are already spent
444 int64_t nOrderPos; // position in ordered transaction list
447 mutable bool fDebitCached;
448 mutable bool fWatchDebitCached;
449 mutable bool fCreditCached;
450 mutable bool fWatchCreditCached;
451 mutable bool fAvailableCreditCached;
452 mutable bool fImmatureCreditCached;
453 mutable bool fImmatureWatchCreditCached;
454 mutable bool fAvailableWatchCreditCached;
455 mutable bool fChangeCached;
456 mutable int64_t nDebitCached;
457 mutable int64_t nWatchDebitCached;
458 mutable int64_t nCreditCached;
459 mutable int64_t nWatchCreditCached;
460 mutable int64_t nAvailableCreditCached;
461 mutable int64_t nImmatureCreditCached;
462 mutable int64_t nImmatureWatchCreditCached;
463 mutable int64_t nAvailableWatchCreditCached;
464 mutable int64_t nChangeCached;
471 CWalletTx(const CWallet* pwalletIn)
476 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
481 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
486 void Init(const CWallet* pwalletIn)
492 fTimeReceivedIsTxTime = false;
496 strFromAccount.clear();
498 fDebitCached = false;
499 fWatchDebitCached = false;
500 fCreditCached = false;
501 fWatchCreditCached = false;
502 fAvailableCreditCached = false;
503 fAvailableWatchCreditCached = false;
504 fImmatureCreditCached = false;
505 fImmatureWatchCreditCached = false;
506 fChangeCached = false;
508 nWatchDebitCached = 0;
510 nWatchCreditCached = 0;
511 nAvailableCreditCached = 0;
512 nAvailableWatchCreditCached = 0;
513 nImmatureCreditCached = 0;
514 nImmatureWatchCreditCached = 0;
521 CWalletTx* pthis = const_cast<CWalletTx*>(this);
528 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
531 BOOST_FOREACH(char f, vfSpent)
533 str += (f ? '1' : '0');
537 pthis->mapValue["spent"] = str;
539 WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
542 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
545 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
548 READWRITE(vOrderForm);
549 READWRITE(fTimeReceivedIsTxTime);
550 READWRITE(nTimeReceived);
556 pthis->strFromAccount = pthis->mapValue["fromaccount"];
558 if (mapValue.count("spent"))
559 BOOST_FOREACH(char c, pthis->mapValue["spent"])
560 pthis->vfSpent.push_back(c != '0');
562 pthis->vfSpent.assign(vout.size(), fSpent);
564 ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
566 pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
569 pthis->mapValue.erase("fromaccount");
570 pthis->mapValue.erase("version");
571 pthis->mapValue.erase("spent");
572 pthis->mapValue.erase("n");
573 pthis->mapValue.erase("timesmart");
576 // marks certain txout's as spent
577 // returns true if any update took place
578 bool UpdateSpent(const std::vector<char>& vfNewSpent)
580 bool fReturn = false;
581 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
583 if (i == vfSpent.size())
586 if (vfNewSpent[i] && !vfSpent[i])
590 fAvailableCreditCached = fAvailableWatchCreditCached = false;
596 // make sure balances are recalculated
599 fCreditCached = false;
600 fAvailableCreditCached = fAvailableWatchCreditCached = false;
601 fDebitCached = fWatchDebitCached = false;
602 fChangeCached = false;
605 void BindWallet(CWallet *pwalletIn)
611 void MarkSpent(unsigned int nOut)
613 if (nOut >= vout.size())
614 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
615 vfSpent.resize(vout.size());
618 vfSpent[nOut] = true;
619 fAvailableCreditCached = fAvailableWatchCreditCached = false;
623 void MarkUnspent(unsigned int nOut)
625 if (nOut >= vout.size())
626 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
627 vfSpent.resize(vout.size());
630 vfSpent[nOut] = false;
631 fAvailableCreditCached = fAvailableWatchCreditCached = false;
635 bool IsSpent(unsigned int nOut) const
637 if (nOut >= vout.size())
638 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
639 if (nOut >= vfSpent.size())
641 return (!!vfSpent[nOut]);
644 int64_t GetDebit(const isminefilter& filter) const
650 if (filter & MINE_SPENDABLE)
653 nDebit += nDebitCached;
656 nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
658 nDebit += nDebitCached;
661 if (filter & MINE_WATCH_ONLY)
663 if (fWatchDebitCached)
664 nDebit += nWatchDebitCached;
667 nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
668 fWatchDebitCached = true;
669 nDebit += nWatchDebitCached;
676 int64_t GetCredit(const isminefilter& filter) const
678 // Must wait until coinbase is safely deep enough in the chain before valuing it
679 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
683 if (filter & MINE_SPENDABLE)
685 // GetBalance can assume transactions in mapWallet won't change
687 credit += nCreditCached;
690 nCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
691 fCreditCached = true;
692 credit += nCreditCached;
695 if (filter & MINE_WATCH_ONLY)
697 if (fWatchCreditCached)
698 credit += nWatchCreditCached;
701 nWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
702 fWatchCreditCached = true;
703 credit += nWatchCreditCached;
709 int64_t GetImmatureCredit(bool fUseCache=true) const
711 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
713 if (fUseCache && fImmatureCreditCached)
714 return nImmatureCreditCached;
715 nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
716 fImmatureCreditCached = true;
717 return nImmatureCreditCached;
723 int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const
725 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
727 if (fUseCache && fImmatureWatchCreditCached)
728 return nImmatureWatchCreditCached;
729 nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
730 fImmatureWatchCreditCached = true;
731 return nImmatureWatchCreditCached;
738 int64_t GetAvailableCredit(bool fUseCache=true) const
740 // Must wait until coinbase is safely deep enough in the chain before valuing it
741 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
745 if (fAvailableCreditCached)
746 return nAvailableCreditCached;
750 for (unsigned int i = 0; i < vout.size(); i++)
754 const CTxOut &txout = vout[i];
755 nCredit += pwallet->GetCredit(txout, MINE_SPENDABLE);
756 if (!MoneyRange(nCredit))
757 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
761 nAvailableCreditCached = nCredit;
762 fAvailableCreditCached = true;
767 int64_t GetAvailableWatchCredit(bool fUseCache=true) const
769 // Must wait until coinbase is safely deep enough in the chain before valuing it
770 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
774 if (fAvailableWatchCreditCached)
775 return nAvailableWatchCreditCached;
779 for (unsigned int i = 0; i < vout.size(); i++)
783 const CTxOut &txout = vout[i];
784 nCredit += pwallet->GetCredit(txout, MINE_WATCH_ONLY);
785 if (!MoneyRange(nCredit))
786 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
790 nAvailableWatchCreditCached = nCredit;
791 fAvailableWatchCreditCached = true;
796 int64_t GetChange() const
799 return nChangeCached;
800 nChangeCached = pwallet->GetChange(*this);
801 fChangeCached = true;
802 return nChangeCached;
805 void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
806 std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
808 void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
809 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
811 bool IsFromMe(const isminefilter& filter) const
813 return (GetDebit(filter) > 0);
816 bool IsTrusted() const
818 // Quick answer in most cases
821 if (GetDepthInMainChain() >= 1)
823 if (fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
826 // If no confirmations but it's from us, we can still
827 // consider it confirmed if all dependencies are confirmed
828 std::map<uint256, const CMerkleTx*> mapPrev;
829 std::vector<const CMerkleTx*> vWorkQueue;
830 vWorkQueue.reserve(vtxPrev.size()+1);
831 vWorkQueue.push_back(this);
832 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
834 const CMerkleTx* ptx = vWorkQueue[i];
838 if (ptx->GetDepthInMainChain() >= 1)
840 if (!pwallet->IsFromMe(*ptx))
845 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
846 mapPrev[tx.GetHash()] = &tx;
849 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
851 if (!mapPrev.count(txin.prevout.hash))
853 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
862 int64_t GetTxTime() const;
863 int GetRequestCount() const;
865 void AddSupportingTransactions(CTxDB& txdb);
867 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
868 bool AcceptWalletTransaction();
870 void RelayWalletTransaction(CTxDB& txdb);
871 void RelayWalletTransaction();
885 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
887 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
890 std::string ToString() const
892 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());
897 printf("%s\n", ToString().c_str());
904 /** Private key that includes an expiration date in case it never gets used. */
909 int64_t nTimeCreated;
910 int64_t nTimeExpires;
911 std::string strComment;
912 //// todo: add something to note what created it (user, getnewaddress, change)
913 //// maybe should have a map<string, string> property map
915 CWalletKey(int64_t nExpires=0)
917 nTimeCreated = (nExpires ? GetTime() : 0);
918 nTimeExpires = nExpires;
923 if (!(nType & SER_GETHASH))
925 READWRITE(vchPrivKey);
926 READWRITE(nTimeCreated);
927 READWRITE(nTimeExpires);
928 READWRITE(strComment);
937 /** Account information.
938 * Stored in wallet with key "acc"+string account name.
952 vchPubKey = CPubKey();
957 if (!(nType & SER_GETHASH))
959 READWRITE(vchPubKey);
965 /** Internal transfers.
966 * Database key is acentry<account><counter>.
968 class CAccountingEntry
971 std::string strAccount;
972 int64_t nCreditDebit;
974 std::string strOtherAccount;
975 std::string strComment;
977 int64_t nOrderPos; // position in ordered transaction list
990 strOtherAccount.clear();
997 CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
998 if (!(nType & SER_GETHASH))
1000 // Note: strAccount is serialized as part of the key, not here.
1001 READWRITE(nCreditDebit);
1003 READWRITE(strOtherAccount);
1007 WriteOrderPos(nOrderPos, me.mapValue);
1009 if (!(mapValue.empty() && _ssExtra.empty()))
1011 CDataStream ss(nType, nVersion);
1012 ss.insert(ss.begin(), '\0');
1014 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
1015 me.strComment.append(ss.str());
1019 READWRITE(strComment);
1021 size_t nSepPos = strComment.find("\0", 0, 1);
1024 me.mapValue.clear();
1025 if (std::string::npos != nSepPos)
1027 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
1029 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
1031 ReadOrderPos(me.nOrderPos, me.mapValue);
1033 if (std::string::npos != nSepPos)
1034 me.strComment.erase(nSepPos);
1036 me.mapValue.erase("n");
1040 std::vector<char> _ssExtra;
1043 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);