Anoncoin  0.9.4
P2P Digital Currency
wallet.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 The Bitcoin developers
3 // Copyright (c) 2013-2014 The Anoncoin Core developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef ANONCOIN_WALLET_H
7 #define ANONCOIN_WALLET_H
8 
9 #include "core.h"
10 #include "crypter.h"
11 #include "key.h"
12 #include "keystore.h"
13 #include "main.h"
14 #include "ui_interface.h"
15 #include "util.h"
16 #include "walletdb.h"
17 
18 #include <algorithm>
19 #include <map>
20 #include <set>
21 #include <stdexcept>
22 #include <stdint.h>
23 #include <string>
24 #include <utility>
25 #include <vector>
26 
27 // Settings
28 extern int64_t nTransactionFee;
29 extern bool bSpendZeroConfChange;
30 
31 // -paytxfee default
32 static const int64_t DEFAULT_TRANSACTION_FEE = 0;
33 // -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
34 static const int nHighTransactionFeeWarning = 0.01 * COIN;
35 
36 class CAccountingEntry;
37 class CCoinControl;
38 class COutput;
39 class CReserveKey;
40 class CScript;
41 class CWalletTx;
42 
45 {
46  FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
47 
48  FEATURE_WALLETCRYPT = 40000, // wallet encryption
49  FEATURE_COMPRPUBKEY = 60000, // compressed public keys
50 
52 };
53 
54 
56 class CKeyPool
57 {
58 public:
59  int64_t nTime;
61 
63  {
64  nTime = GetTime();
65  }
66 
67  CKeyPool(const CPubKey& vchPubKeyIn)
68  {
69  nTime = GetTime();
70  vchPubKey = vchPubKeyIn;
71  }
72 
74  (
75  if (!(nType & SER_GETHASH))
76  READWRITE(nVersion);
77  READWRITE(nTime);
78  READWRITE(vchPubKey);
79  )
80 };
81 
84 {
85 public:
86  std::string name;
87  std::string purpose;
88 
90  {
91  purpose = "unknown";
92  }
93 
94  typedef std::map<std::string, std::string> StringMap;
95  StringMap destdata;
96 };
97 
102 {
103 private:
104  bool SelectCoins(int64_t nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl *coinControl = NULL) const;
105 
107 
108  // the current wallet version: clients below this version are not able to load the wallet
110 
111  // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
113 
114  int64_t nNextResend;
115  int64_t nLastResend;
116 
117  // Used to keep track of spent outpoints, and
118  // detect and report conflicts (double-spends or
119  // mutated transactions where the mutant gets mined).
120  typedef std::multimap<COutPoint, uint256> TxSpends;
121  TxSpends mapTxSpends;
122  void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
123  void AddToSpends(const uint256& wtxid);
124 
125  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
126 
127 public:
134 
136  std::string strWalletFile;
137 
138  std::set<int64_t> setKeyPool;
139  std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
140 
141  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
142  MasterKeyMap mapMasterKeys;
143  unsigned int nMasterKeyMaxID;
144 
146  {
147  SetNull();
148  }
149  CWallet(std::string strWalletFileIn)
150  {
151  SetNull();
152 
153  strWalletFile = strWalletFileIn;
154  fFileBacked = true;
155  }
156  void SetNull()
157  {
158  nWalletVersion = FEATURE_BASE;
159  nWalletMaxVersion = FEATURE_BASE;
160  fFileBacked = false;
161  nMasterKeyMaxID = 0;
162  pwalletdbEncryption = NULL;
163  nOrderPosNext = 0;
164  nNextResend = 0;
165  nLastResend = 0;
166  nTimeFirstKey = 0;
167  }
168 
169  std::map<uint256, CWalletTx> mapWallet;
170 
171  int64_t nOrderPosNext;
172  std::map<uint256, int> mapRequestCount;
173 
174  std::map<CTxDestination, CAddressBookData> mapAddressBook;
175 
177 
178  std::set<COutPoint> setLockedCoins;
179 
180  int64_t nTimeFirstKey;
181 
182  const CWalletTx* GetWalletTx(const uint256& hash) const;
183 
184  // check whether we are allowed to upgrade (or already support) to the named feature
185  bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
186 
187  void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL) const;
188  bool SelectCoinsMinConf(int64_t nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
189 
190  bool IsSpent(const uint256& hash, unsigned int n) const;
191 
192  bool IsLockedCoin(uint256 hash, unsigned int n) const;
193  void LockCoin(COutPoint& output);
194  void UnlockCoin(COutPoint& output);
195  void UnlockAllCoins();
196  void ListLockedCoins(std::vector<COutPoint>& vOutpts);
197 
198  // keystore implementation
199  // Generate a new key
200  CPubKey GenerateNewKey();
201  // Adds a key to the store, and saves it to disk.
202  bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
203  // Adds a key to the store, without saving it to disk (used by LoadWallet)
204  bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
205  // Load metadata (used by LoadWallet)
206  bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
207 
208  bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
209 
210  // Adds an encrypted key to the store, and saves it to disk.
211  bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
212  // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
213  bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
214  bool AddCScript(const CScript& redeemScript);
215  bool LoadCScript(const CScript& redeemScript);
216 
218  bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
220  bool EraseDestData(const CTxDestination &dest, const std::string &key);
222  bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
224  bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
225 
226  // Adds a watch-only address to the store, and saves it to disk.
227  bool AddWatchOnly(const CScript &dest);
228  bool RemoveWatchOnly(const CScript &dest);
229  // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
230  bool LoadWatchOnly(const CScript &dest);
231 
232  bool Unlock(const SecureString& strWalletPassphrase);
233  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
234  bool EncryptWallet(const SecureString& strWalletPassphrase);
235 
236  void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
237 
241  int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
242 
243  typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
244  typedef std::multimap<int64_t, TxPair > TxItems;
245 
250  TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
251 
252  void MarkDirty();
253  bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet=false);
254  void SyncTransaction(const uint256 &hash, const CTransaction& tx, const CBlock* pblock);
255  bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate);
256  void EraseFromWallet(const uint256 &hash);
257  int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
258  void ReacceptWalletTransactions();
259  void ResendWalletTransactions();
260  int64_t GetBalance() const;
261  int64_t GetUnconfirmedBalance() const;
262  int64_t GetImmatureBalance() const;
263  int64_t GetWatchOnlyBalance() const;
264  int64_t GetUnconfirmedWatchOnlyBalance() const;
265  int64_t GetImmatureWatchOnlyBalance() const;
266  bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend,
267  CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl *coinControl = NULL);
268  bool CreateTransaction(CScript scriptPubKey, int64_t nValue,
269  CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl *coinControl = NULL);
270  bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
271  std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew);
272  std::string SendMoneyToDestination(const CTxDestination &address, int64_t nValue, CWalletTx& wtxNew);
273 
274  bool NewKeyPool();
275  bool TopUpKeyPool(unsigned int kpSize = 0);
276  int64_t AddReserveKey(const CKeyPool& keypool);
277  void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
278  void KeepKey(int64_t nIndex);
279  void ReturnKey(int64_t nIndex);
280  bool GetKeyFromPool(CPubKey &key);
281  int64_t GetOldestKeyPoolTime();
282  void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
283 
284  std::set< std::set<CTxDestination> > GetAddressGroupings();
285  std::map<CTxDestination, int64_t> GetAddressBalances();
286 
287  std::set<CTxDestination> GetAccountAddresses(std::string strAccount) const;
288 
289  isminetype IsMine(const CTxIn& txin) const;
290  int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
291  isminetype IsMine(const CTxOut& txout) const
292  {
293  return ::IsMine(*this, txout.scriptPubKey);
294  }
295  int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const
296  {
297  if (!MoneyRange(txout.nValue))
298  throw std::runtime_error("CWallet::GetCredit() : value out of range");
299  return ((IsMine(txout) & filter) ? txout.nValue : 0);
300  }
301  bool IsChange(const CTxOut& txout) const;
302  int64_t GetChange(const CTxOut& txout) const
303  {
304  if (!MoneyRange(txout.nValue))
305  throw std::runtime_error("CWallet::GetChange() : value out of range");
306  return (IsChange(txout) ? txout.nValue : 0);
307  }
308  bool IsMine(const CTransaction& tx) const
309  {
310  BOOST_FOREACH(const CTxOut& txout, tx.vout)
311  if (IsMine(txout))
312  return true;
313  return false;
314  }
315  bool IsFromMe(const CTransaction& tx) const // should probably be renamed to IsRelevantToMe
316  {
317  return (GetDebit(tx, ISMINE_ALL) > 0);
318  }
319  int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const
320  {
321  int64_t nDebit = 0;
322  BOOST_FOREACH(const CTxIn& txin, tx.vin)
323  {
324  nDebit += GetDebit(txin, filter);
325  if (!MoneyRange(nDebit))
326  throw std::runtime_error("CWallet::GetDebit() : value out of range");
327  }
328  return nDebit;
329  }
330  int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const
331  {
332  int64_t nCredit = 0;
333  BOOST_FOREACH(const CTxOut& txout, tx.vout)
334  {
335  nCredit += GetCredit(txout, filter);
336  if (!MoneyRange(nCredit))
337  throw std::runtime_error("CWallet::GetCredit() : value out of range");
338  }
339  return nCredit;
340  }
341  int64_t GetChange(const CTransaction& tx) const
342  {
343  int64_t nChange = 0;
344  BOOST_FOREACH(const CTxOut& txout, tx.vout)
345  {
346  nChange += GetChange(txout);
347  if (!MoneyRange(nChange))
348  throw std::runtime_error("CWallet::GetChange() : value out of range");
349  }
350  return nChange;
351  }
352  void SetBestChain(const CBlockLocator& loc);
353 
354  DBErrors LoadWallet(bool& fFirstRunRet);
355  DBErrors ZapWalletTx();
356 
357  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
358 
359  bool DelAddressBook(const CTxDestination& address);
360 
361  void UpdatedTransaction(const uint256 &hashTx);
362 
363  void Inventory(const uint256 &hash)
364  {
365  {
366  LOCK(cs_wallet);
367  std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
368  if (mi != mapRequestCount.end())
369  (*mi).second++;
370  }
371  }
372 
373  unsigned int GetKeyPoolSize()
374  {
375  AssertLockHeld(cs_wallet); // setKeyPool
376  return setKeyPool.size();
377  }
378 
379  bool SetDefaultKey(const CPubKey &vchPubKey);
380 
381  // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
382  bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
383 
384  // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
385  bool SetMaxVersion(int nVersion);
386 
387  // get the current wallet format (the oldest client version guaranteed to understand this wallet)
388  int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
389 
390  // Get wallet transactions that conflict with given transaction (spend same outputs)
391  std::set<uint256> GetConflicts(const uint256& txid) const;
392 
396  boost::signals2::signal<void (CWallet *wallet, const CTxDestination
397  &address, const std::string &label, bool isMine,
398  const std::string &purpose,
400 
404  boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
406 
408  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
409 
411  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
412 };
413 
416 {
417 protected:
419  int64_t nIndex;
421 public:
422  CReserveKey(CWallet* pwalletIn)
423  {
424  nIndex = -1;
425  pwallet = pwalletIn;
426  }
427 
429  {
430  ReturnKey();
431  }
432 
433  void ReturnKey();
434  bool GetReservedKey(CPubKey &pubkey);
435  void KeepKey();
436 };
437 
438 
439 typedef std::map<std::string, std::string> mapValue_t;
440 
441 
442 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
443 {
444  if (!mapValue.count("n"))
445  {
446  nOrderPos = -1; // TODO: calculate elsewhere
447  return;
448  }
449  nOrderPos = atoi64(mapValue["n"].c_str());
450 }
451 
452 
453 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
454 {
455  if (nOrderPos == -1)
456  return;
457  mapValue["n"] = i64tostr(nOrderPos);
458 }
459 
460 
464 class CWalletTx : public CMerkleTx
465 {
466 private:
467  const CWallet* pwallet;
468 
469 public:
470  mapValue_t mapValue;
471  std::vector<std::pair<std::string, std::string> > vOrderForm;
472  unsigned int fTimeReceivedIsTxTime;
473  unsigned int nTimeReceived; // time received by this node
474  unsigned int nTimeSmart;
475  char fFromMe;
476  std::string strFromAccount;
477  int64_t nOrderPos; // position in ordered transaction list
478 
479  // memory only
480  mutable bool fDebitCached;
481  mutable bool fCreditCached;
482  mutable bool fImmatureCreditCached;
484  mutable bool fWatchDebitCached;
485  mutable bool fWatchCreditCached;
488  mutable bool fChangeCached;
489  mutable int64_t nDebitCached;
490  mutable int64_t nCreditCached;
491  mutable int64_t nImmatureCreditCached;
492  mutable int64_t nAvailableCreditCached;
493  mutable int64_t nWatchDebitCached;
494  mutable int64_t nWatchCreditCached;
495  mutable int64_t nImmatureWatchCreditCached;
497  mutable int64_t nChangeCached;
498 
500  {
501  Init(NULL);
502  }
503 
504  CWalletTx(const CWallet* pwalletIn)
505  {
506  Init(pwalletIn);
507  }
508 
509  CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
510  {
511  Init(pwalletIn);
512  }
513 
514  CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
515  {
516  Init(pwalletIn);
517  }
518 
519  void Init(const CWallet* pwalletIn)
520  {
521  pwallet = pwalletIn;
522  mapValue.clear();
523  vOrderForm.clear();
524  fTimeReceivedIsTxTime = false;
525  nTimeReceived = 0;
526  nTimeSmart = 0;
527  fFromMe = false;
528  strFromAccount.clear();
529  fDebitCached = false;
530  fCreditCached = false;
531  fImmatureCreditCached = false;
532  fAvailableCreditCached = false;
533  fWatchDebitCached = false;
534  fWatchCreditCached = false;
535  fImmatureWatchCreditCached = false;
536  fAvailableWatchCreditCached = false;
537  fChangeCached = false;
538  nDebitCached = 0;
539  nCreditCached = 0;
540  nImmatureCreditCached = 0;
541  nAvailableCreditCached = 0;
542  nWatchDebitCached = 0;
543  nWatchCreditCached = 0;
544  nAvailableWatchCreditCached = 0;
545  nImmatureWatchCreditCached = 0;
546  nChangeCached = 0;
547  nOrderPos = -1;
548  }
549 
551  (
552  CWalletTx* pthis = const_cast<CWalletTx*>(this);
553  if (fRead)
554  pthis->Init(NULL);
555  char fSpent = false;
556 
557  if (!fRead)
558  {
559  pthis->mapValue["fromaccount"] = pthis->strFromAccount;
560 
561  WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
562 
563  if (nTimeSmart)
564  pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
565  }
566 
567  nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
568  std::vector<CMerkleTx> vUnused; // Used to be vtxPrev
569  READWRITE(vUnused);
570  READWRITE(mapValue);
571  READWRITE(vOrderForm);
572  READWRITE(fTimeReceivedIsTxTime);
573  READWRITE(nTimeReceived);
574  READWRITE(fFromMe);
575  READWRITE(fSpent);
576 
577  if (fRead)
578  {
579  pthis->strFromAccount = pthis->mapValue["fromaccount"];
580 
581  ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
582 
583  pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
584  }
585 
586  pthis->mapValue.erase("fromaccount");
587  pthis->mapValue.erase("version");
588  pthis->mapValue.erase("spent");
589  pthis->mapValue.erase("n");
590  pthis->mapValue.erase("timesmart");
591  )
592 
593  // make sure balances are recalculated
594  void MarkDirty()
595  {
596  fCreditCached = false;
597  fAvailableCreditCached = false;
598  fWatchDebitCached = false;
599  fWatchCreditCached = false;
600  fAvailableWatchCreditCached = false;
601  fImmatureWatchCreditCached = false;
602  fDebitCached = false;
603  fChangeCached = false;
604  }
605 
606  void BindWallet(CWallet *pwalletIn)
607  {
608  pwallet = pwalletIn;
609  MarkDirty();
610  }
611 
612  // filter decides which addresses will count towards the debit
613  int64_t GetDebit(const isminefilter& filter) const
614  {
615  if (vin.empty())
616  return 0;
617 
618  int64_t debit = 0;
619  if(filter & ISMINE_SPENDABLE)
620  {
621  if (fDebitCached)
622  debit += nDebitCached;
623  else
624  {
625  nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
626  fDebitCached = true;
627  debit += nDebitCached;
628  }
629  }
630  if(filter & ISMINE_WATCH_ONLY)
631  {
632  if(fWatchDebitCached)
633  debit += nWatchDebitCached;
634  else
635  {
636  nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
637  fWatchDebitCached = true;
638  debit += nWatchDebitCached;
639  }
640  }
641  return debit;
642  }
643 
644  int64_t GetCredit(const isminefilter& filter) const
645  {
646  // Must wait until coinbase is safely deep enough in the chain before valuing it
647  if (IsCoinBase() && GetBlocksToMaturity() > 0)
648  return 0;
649 
650  int64_t credit = 0;
651  if(filter & ISMINE_SPENDABLE)
652  {
653  // GetBalance can assume transactions in mapWallet won't change
654  if (fCreditCached)
655  credit += nCreditCached;
656  else
657  {
658  nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
659  fCreditCached = true;
660  credit += nCreditCached;
661  }
662  }
663  if(filter & ISMINE_WATCH_ONLY)
664  {
665  if(fWatchCreditCached)
666  credit += nWatchCreditCached;
667  else
668  {
669  nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
670  fWatchCreditCached = true;
671  credit += nWatchCreditCached;
672  }
673  }
674  return credit;
675  }
676 
677  int64_t GetImmatureCredit(bool fUseCache=true) const
678  {
679  if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
680  {
681  if (fUseCache && fImmatureCreditCached)
682  return nImmatureCreditCached;
683  nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
684  fImmatureCreditCached = true;
685  return nImmatureCreditCached;
686  }
687 
688  return 0;
689  }
690 
691  int64_t GetAvailableCredit(bool fUseCache=true) const
692  {
693  if (pwallet == 0)
694  return 0;
695 
696  // Must wait until coinbase is safely deep enough in the chain before valuing it
697  if (IsCoinBase() && GetBlocksToMaturity() > 0)
698  return 0;
699 
700  if (fUseCache && fAvailableCreditCached)
701  return nAvailableCreditCached;
702 
703  int64_t nCredit = 0;
704  uint256 hashTx = GetHash();
705  for (unsigned int i = 0; i < vout.size(); i++)
706  {
707  if (!pwallet->IsSpent(hashTx, i))
708  {
709  const CTxOut &txout = vout[i];
710  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
711  if (!MoneyRange(nCredit))
712  throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
713  }
714  }
715 
716  nAvailableCreditCached = nCredit;
717  fAvailableCreditCached = true;
718  return nCredit;
719  }
720 
721  int64_t GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const
722  {
723  if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
724  {
725  if (fUseCache && fImmatureWatchCreditCached)
726  return nImmatureWatchCreditCached;
727  nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
728  fImmatureWatchCreditCached = true;
729  return nImmatureWatchCreditCached;
730  }
731 
732  return 0;
733  }
734 
735  int64_t GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const
736  {
737  if (pwallet == 0)
738  return 0;
739 
740  // Must wait until coinbase is safely deep enough in the chain before valuing it
741  if (IsCoinBase() && GetBlocksToMaturity() > 0)
742  return 0;
743 
744  if (fUseCache && fAvailableWatchCreditCached)
745  return nAvailableWatchCreditCached;
746 
747  int64_t nCredit = 0;
748  for (unsigned int i = 0; i < vout.size(); i++)
749  {
750  if (!pwallet->IsSpent(GetHash(), i))
751  {
752  const CTxOut &txout = vout[i];
753  nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
754  if (!MoneyRange(nCredit))
755  throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
756  }
757  }
758 
759  nAvailableWatchCreditCached = nCredit;
760  fAvailableWatchCreditCached = true;
761  return nCredit;
762  }
763 
764  int64_t GetChange() const
765  {
766  if (fChangeCached)
767  return nChangeCached;
768  nChangeCached = pwallet->GetChange(*this);
769  fChangeCached = true;
770  return nChangeCached;
771  }
772 
773  void GetAmounts(std::list<std::pair<CTxDestination, int64_t> >& listReceived,
774  std::list<std::pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
775 
776  void GetAccountAmounts(const std::string& strAccount, int64_t& nReceived,
777  int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
778 
779  bool IsFromMe(const isminefilter& filter) const
780  {
781  return (GetDebit(filter) > 0);
782  }
783 
784  bool IsTrusted() const
785  {
786  // Quick answer in most cases
787  if (!IsFinalTx(*this))
788  return false;
789  int nDepth = GetDepthInMainChain();
790  if (nDepth >= 1)
791  return true;
792  if (nDepth < 0)
793  return false;
794  if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
795  return false;
796 
797  // Trusted if all inputs are from us and are in the mempool:
798  BOOST_FOREACH(const CTxIn& txin, vin)
799  {
800  // Transactions not sent by us: not trusted
801  const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
802  if (parent == NULL)
803  return false;
804  const CTxOut& parentOut = parent->vout[txin.prevout.n];
805  if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
806  return false;
807  }
808  return true;
809  }
810 
811  bool WriteToDisk();
812 
813  int64_t GetTxTime() const;
814  int GetRequestCount() const;
815 
816  void RelayWalletTransaction();
817 
818  std::set<uint256> GetConflicts() const;
819 };
820 
821 
822 
823 
824 class COutput
825 {
826 public:
827  const CWalletTx *tx;
828  int i;
829  int nDepth;
831 
832  COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
833  {
834  tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
835  }
836 
837  std::string ToString() const
838  {
839  return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
840  }
841 
842  void print() const
843  {
844  LogPrintf("%s\n", ToString().c_str());
845  }
846 };
847 
848 
849 
850 
853 {
854 public:
856  int64_t nTimeCreated;
857  int64_t nTimeExpires;
858  std::string strComment;
861 
862  CWalletKey(int64_t nExpires=0)
863  {
864  nTimeCreated = (nExpires ? GetTime() : 0);
865  nTimeExpires = nExpires;
866  }
867 
869  (
870  if (!(nType & SER_GETHASH))
871  READWRITE(nVersion);
872  READWRITE(vchPrivKey);
873  READWRITE(nTimeCreated);
874  READWRITE(nTimeExpires);
875  READWRITE(LIMITED_STRING(strComment, 65536));
876  )
877 };
878 
879 
880 
881 
882 
883 
887 class CAccount
888 {
889 public:
891 
893  {
894  SetNull();
895  }
896 
897  void SetNull()
898  {
899  vchPubKey = CPubKey();
900  }
901 
903  (
904  if (!(nType & SER_GETHASH))
905  READWRITE(nVersion);
906  READWRITE(vchPubKey);
907  )
908 };
909 
910 
911 
916 {
917 public:
918  std::string strAccount;
919  int64_t nCreditDebit;
920  int64_t nTime;
921  std::string strOtherAccount;
922  std::string strComment;
923  mapValue_t mapValue;
924  int64_t nOrderPos; // position in ordered transaction list
925  uint64_t nEntryNo;
926 
928  {
929  SetNull();
930  }
931 
932  void SetNull()
933  {
934  nCreditDebit = 0;
935  nTime = 0;
936  strAccount.clear();
937  strOtherAccount.clear();
938  strComment.clear();
939  nOrderPos = -1;
940  }
941 
943  (
944  CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
945  if (!(nType & SER_GETHASH))
946  READWRITE(nVersion);
947  // Note: strAccount is serialized as part of the key, not here.
948  READWRITE(nCreditDebit);
949  READWRITE(nTime);
950  READWRITE(LIMITED_STRING(strOtherAccount, 65536));
951 
952  if (!fRead)
953  {
954  WriteOrderPos(nOrderPos, me.mapValue);
955 
956  if (!(mapValue.empty() && _ssExtra.empty()))
957  {
958  CDataStream ss(nType, nVersion);
959  ss.insert(ss.begin(), '\0');
960  ss << mapValue;
961  ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
962  me.strComment.append(ss.str());
963  }
964  }
965 
966  READWRITE(LIMITED_STRING(strComment, 65536));
967 
968  size_t nSepPos = strComment.find("\0", 0, 1);
969  if (fRead)
970  {
971  me.mapValue.clear();
972  if (std::string::npos != nSepPos)
973  {
974  CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
975  ss >> me.mapValue;
976  me._ssExtra = std::vector<char>(ss.begin(), ss.end());
977  }
978  ReadOrderPos(me.nOrderPos, me.mapValue);
979  }
980  if (std::string::npos != nSepPos)
981  me.strComment.erase(nSepPos);
982 
983  me.mapValue.erase("n");
984  )
985 
986 private:
987  std::vector<char> _ssExtra;
988 };
989 
990 #endif
int64_t nTimeCreated
Definition: wallet.h:856
bool fChangeCached
Definition: wallet.h:488
int64_t GetImmatureWatchOnlyCredit(const bool &fUseCache=true) const
Definition: wallet.h:721
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Definition: main.cpp:617
const CWallet * pwallet
Definition: wallet.h:467
bool IsMine(const CTransaction &tx) const
Definition: wallet.h:308
CWallet * pwallet
Definition: wallet.h:418
int64_t GetCredit(const CTxOut &txout, const isminefilter &filter) const
Definition: wallet.h:295
int64_t nNextResend
Definition: wallet.h:114
Account information.
Definition: wallet.h:887
std::set< int64_t > setKeyPool
Definition: wallet.h:138
int i
Definition: wallet.h:828
int64_t nOrderPos
Definition: wallet.h:924
void BindWallet(CWallet *pwalletIn)
Definition: wallet.h:606
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:691
unsigned int SerReadWrite(Stream &s, const T &obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
Definition: serialize.h:806
int64_t GetChange(const CTransaction &tx) const
Definition: wallet.h:341
CPrivKey vchPrivKey
Definition: wallet.h:855
int64_t nIndex
Definition: wallet.h:419
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: core.h:457
CScript scriptPubKey
Definition: core.h:125
#define READWRITE(obj)
Definition: serialize.h:101
char fFromMe
Definition: wallet.h:475
int64_t GetChange() const
Definition: wallet.h:764
Definition: core.h:394
int64_t GetCredit(const CTransaction &tx, const isminefilter &filter) const
Definition: wallet.h:330
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:174
CCriticalSection cs_wallet
Main wallet lock.
Definition: wallet.h:133
int64_t nTransactionFee
Definition: wallet.cpp:20
#define strprintf
Definition: tinyformat.h:1011
isminetype IsMine(const CKeyStore &keystore, const CTxDestination &dest)
Definition: script.cpp:1450
bool fImmatureCreditCached
Definition: wallet.h:482
std::string strFromAccount
Definition: wallet.h:476
WalletFeature
(client) version numbers for particular wallet features
Definition: wallet.h:44
CPubKey vchDefaultKey
Definition: wallet.h:176
CWalletDB * pwalletdbEncryption
Definition: wallet.h:106
std::multimap< COutPoint, uint256 > TxSpends
Definition: wallet.h:120
bool IsFromMe(const CTransaction &tx) const
Definition: wallet.h:315
int64_t nImmatureCreditCached
Definition: wallet.h:491
int64_t nOrderPos
Definition: wallet.h:477
int64_t nDebitCached
Definition: wallet.h:489
std::string i64tostr(int64_t n)
Definition: util.h:207
uint256 GetHash() const
Definition: core.cpp:76
int64_t nTimeFirstKey
Definition: wallet.h:180
mapValue_t mapValue
Definition: wallet.h:923
bool MoneyRange(int64_t nValue)
Definition: core.h:21
void SetNull()
Definition: wallet.h:897
CPubKey vchPubKey
Definition: wallet.h:420
int64_t GetChange(const CTxOut &txout) const
Definition: wallet.h:302
#define IMPLEMENT_SERIALIZE(statements)
Definition: serialize.h:63
unsigned int GetKeyPoolSize()
Definition: wallet.h:373
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:141
Double ended buffer combining vector and stream-like interfaces.
Definition: serialize.h:848
std::string strComment
Definition: wallet.h:858
std::string name
Definition: wallet.h:86
~CReserveKey()
Definition: wallet.h:428
CWalletKey(int64_t nExpires=0)
Definition: wallet.h:862
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
Definition: wallet.h:832
int64_t nChangeCached
Definition: wallet.h:497
unsigned int n
Definition: core.h:28
int64_t nAvailableWatchCreditCached
Definition: wallet.h:496
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:31
Keystore which keeps the private keys encrypted.
Definition: crypter.h:114
string FormatMoney(int64_t n, bool fPlus)
Definition: util.cpp:308
bool IsTrusted() const
Definition: wallet.h:784
bool fSpendable
Definition: wallet.h:830
int64_t nTimeExpires
Definition: wallet.h:857
bool CanSupportFeature(enum WalletFeature wf)
Definition: wallet.h:185
bool fAvailableCreditCached
Definition: wallet.h:483
std::string purpose
Definition: wallet.h:87
Coin Control Features.
Definition: coincontrol.h:12
CAccount()
Definition: wallet.h:892
int64_t GetDebit(const CTxIn &txin, const isminefilter &filter) const
Definition: wallet.cpp:706
mapValue_t mapValue
Definition: wallet.h:470
bool fDebitCached
Definition: wallet.h:480
isminetype
IsMine() return codes.
Definition: script.h:197
std::multimap< int64_t, TxPair > TxItems
Definition: wallet.h:244
bool fAvailableWatchCreditCached
Definition: wallet.h:487
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
Definition: key.h:177
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:405
#define AssertLockHeld(cs)
Definition: sync.h:98
std::string strComment
Definition: wallet.h:922
int64_t GetDebit(const CTransaction &tx, const isminefilter &filter) const
Definition: wallet.h:319
bool IsSpent(const uint256 &hash, unsigned int n) const
Definition: wallet.cpp:357
int64_t nTime
Definition: wallet.h:59
int64_t nCreditCached
Definition: wallet.h:490
#define LogPrintf(...)
Definition: util.h:118
unsigned int nMasterKeyMaxID
Definition: wallet.h:143
int nDepth
Definition: wallet.h:829
uint64_t nEntryNo
Definition: wallet.h:925
ChangeType
General change type (added, updated, removed).
Definition: ui_interface.h:26
An input of a transaction.
Definition: core.h:72
const CWalletTx * GetWalletTx(const uint256 &hash) const
Definition: wallet.cpp:37
int64_t nCreditDebit
Definition: wallet.h:919
#define LOCK(cs)
Definition: sync.h:157
std::vector< CTxOut > vout
Definition: core.h:187
int GetVersion()
Definition: wallet.h:388
CKeyPool()
Definition: wallet.h:62
int64_t atoi64(const char *psz)
Definition: util.h:217
int64_t GetAvailableWatchOnlyCredit(const bool &fUseCache=true) const
Definition: wallet.h:735
std::string ToString() const
Definition: wallet.h:837
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: allocators.h:254
An encapsulated public key.
Definition: key.h:43
void Inventory(const uint256 &hash)
Definition: wallet.h:363
std::set< COutPoint > setLockedCoins
Definition: wallet.h:178
std::vector< CTxIn > vin
Definition: core.h:186
TxSpends mapTxSpends
Definition: wallet.h:121
std::map< std::string, std::string > StringMap
Definition: wallet.h:94
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Definition: wallet.h:204
bool bSpendZeroConfChange
Definition: wallet.cpp:21
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
Definition: crypter.cpp:178
An output of a transaction.
Definition: core.h:121
void SetNull()
Definition: wallet.h:156
std::map< uint256, int > mapRequestCount
Definition: wallet.h:172
CAddressBookData()
Definition: wallet.h:89
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:779
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: core.h:24
bool fWatchCreditCached
Definition: wallet.h:485
uint8_t isminefilter
used for bitflags of isminetype
Definition: script.h:205
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:472
int64_t GetTime()
Definition: util.cpp:1220
bool LoadMinVersion(int nVersion)
Definition: wallet.h:208
Access to the wallet database (wallet.dat)
Definition: walletdb.h:73
bool fCreditCached
Definition: wallet.h:481
int nWalletMaxVersion
Definition: wallet.h:112
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:464
std::string strWalletFile
Definition: wallet.h:136
CWalletTx(const CWallet *pwalletIn, const CMerkleTx &txIn)
Definition: wallet.h:509
CPubKey vchPubKey
Definition: wallet.h:890
int64_t nWatchCreditCached
Definition: wallet.h:494
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: keystore.h:17
int64_t GetCredit(const isminefilter &filter) const
Definition: wallet.h:644
int64_t GetDebit(const isminefilter &filter) const
Definition: wallet.h:613
bool fFileBacked
Definition: wallet.h:135
void print() const
Definition: wallet.h:842
256-bit unsigned integer
Definition: uint256.h:532
void Init(const CWallet *pwalletIn)
Definition: wallet.h:519
CPubKey vchPubKey
Definition: wallet.h:60
CWallet(std::string strWalletFileIn)
Definition: wallet.h:149
CWallet()
Definition: wallet.h:145
isminetype IsMine(const CTxOut &txout) const
Definition: wallet.h:291
boost::signals2::signal< void(CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:399
MasterKeyMap mapMasterKeys
Definition: wallet.h:142
A key allocated from the key pool.
Definition: wallet.h:415
CWalletTx()
Definition: wallet.h:499
Address book data.
Definition: wallet.h:83
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: main.h:698
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
StringMap destdata
Definition: wallet.h:95
int64_t nOrderPosNext
Definition: wallet.h:171
std::string ToString() const
Definition: uint256.h:341
unsigned int nTimeSmart
Definition: wallet.h:474
void SetNull()
Definition: wallet.h:932
CWalletTx(const CWallet *pwalletIn)
Definition: wallet.h:504
Private key that includes an expiration date in case it never gets used.
Definition: wallet.h:852
Internal transfers.
Definition: wallet.h:915
const CWalletTx * tx
Definition: wallet.h:827
#define LIMITED_STRING(obj, n)
Definition: serialize.h:320
int nWalletVersion
Definition: wallet.h:109
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:101
CKeyPool(const CPubKey &vchPubKeyIn)
Definition: wallet.h:67
std::map< CKeyID, CKeyMetadata > mapKeyMetadata
Definition: wallet.h:139
CAccountingEntry()
Definition: wallet.h:927
CReserveKey(CWallet *pwalletIn)
Definition: wallet.h:422
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:169
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:408
CWalletTx(const CWallet *pwalletIn, const CTransaction &txIn)
Definition: wallet.h:514
int64_t nLastResend
Definition: wallet.h:115
unsigned int nTimeReceived
Definition: wallet.h:473
bool fWatchDebitCached
Definition: wallet.h:484
An encapsulated private key.
Definition: key.h:180
int64_t GetAvailableCredit(bool fUseCache=true) const
Definition: wallet.h:691
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: core.h:179
bool fImmatureWatchCreditCached
Definition: wallet.h:486
std::pair< CWalletTx *, CAccountingEntry * > TxPair
Definition: wallet.h:243
int64_t nImmatureWatchCreditCached
Definition: wallet.h:495
COutPoint prevout
Definition: core.h:75
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:411
int64_t nAvailableCreditCached
Definition: wallet.h:492
std::string strOtherAccount
Definition: wallet.h:921
int64_t nWatchDebitCached
Definition: wallet.h:493
int64_t GetImmatureCredit(bool fUseCache=true) const
Definition: wallet.h:677
int64_t nTime
Definition: wallet.h:920
A transaction with a merkle branch linking it to the block chain.
Definition: main.h:436
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:439
int64_t nValue
Definition: core.h:124
A key pool entry.
Definition: wallet.h:56
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:471
uint256 hash
Definition: core.h:27
std::string strAccount
Definition: wallet.h:918