Move some implementations of CWallet methods to wallet.cpp.
[novacoin.git] / src / wallet.h
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
7
8 #include <string>
9 #include <vector>
10
11 #include <stdlib.h>
12
13 #include "main.h"
14 #include "key.h"
15 #include "keystore.h"
16 #include "script.h"
17 #include "ui_interface.h"
18 #include "util.h"
19 #include "walletdb.h"
20 #include "base58.h"
21
22 extern unsigned int nStakeMaxAge;
23 extern bool fWalletUnlockMintOnly;
24 extern bool fConfChange;
25 class CAccountingEntry;
26 class CWalletTx;
27 class CReserveKey;
28 class COutput;
29 class CCoinControl;
30
31 // Set of selected transactions
32 typedef std::set<std::pair<const CWalletTx*,unsigned int> > CoinsSet;
33
34 /** (client) version numbers for particular wallet features */
35 enum WalletFeature
36 {
37     FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
38
39     FEATURE_WALLETCRYPT = 40000, // wallet encryption
40     FEATURE_COMPRPUBKEY = 60000, // compressed public keys
41     FEATURE_MALLKEY = 60017,
42     FEATURE_LATEST = 60017
43 };
44
45 /** A key pool entry */
46 class CKeyPool
47 {
48 public:
49     int64_t nTime;
50     CPubKey vchPubKey;
51
52     CKeyPool()
53     {
54         nTime = GetTime();
55     }
56
57     CKeyPool(const CPubKey& vchPubKeyIn)
58     {
59         nTime = GetTime();
60         vchPubKey = vchPubKeyIn;
61     }
62
63     IMPLEMENT_SERIALIZE
64     (
65         if (!(nType & SER_GETHASH))
66             READWRITE(nVersion);
67         READWRITE(nTime);
68         READWRITE(vchPubKey);
69     )
70 };
71
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.
74  */
75 class CWallet : public CCryptoKeyStore
76 {
77 private:
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;
79
80     CWalletDB *pwalletdbEncryption, *pwalletdbDecryption;
81
82     // the current wallet version: clients below this version are not able to load the wallet
83     int nWalletVersion;
84
85     // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
86     int nWalletMaxVersion;
87
88     // stake mining statistics
89     uint64_t nKernelsTried;
90     uint64_t nCoinDaysTried;
91
92 public:
93     mutable CCriticalSection cs_wallet;
94
95     bool fFileBacked;
96     std::string strWalletFile;
97
98     std::set<int64_t> setKeyPool;
99     /*
100     std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
101     std::map<CMalleableKeyView, CKeyMetadata> mapMalleableKeyMetadata;
102     */
103
104     std::map<CBitcoinAddress, CKeyMetadata> mapKeyMetadata;
105
106     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
107     MasterKeyMap mapMasterKeys;
108     unsigned int nMasterKeyMaxID;
109
110     CWallet()
111     {
112         SetNull();
113     }
114     CWallet(std::string strWalletFileIn)
115     {
116         SetNull();
117
118         strWalletFile = strWalletFileIn;
119         fFileBacked = true;
120     }
121     void SetNull()
122     {
123         nWalletVersion = FEATURE_BASE;
124         nWalletMaxVersion = FEATURE_BASE;
125         fFileBacked = false;
126         nMasterKeyMaxID = 0;
127         pwalletdbEncryption = NULL;
128         pwalletdbDecryption = NULL;
129         nOrderPosNext = 0;
130         nKernelsTried = 0;
131         nCoinDaysTried = 0;
132         nTimeFirstKey = 0;
133     }
134
135     std::map<uint256, CWalletTx> mapWallet;
136     std::vector<uint256> vMintingWalletUpdated;
137     int64_t nOrderPosNext;
138     std::map<uint256, int> mapRequestCount;
139
140     std::map<CBitcoinAddress, std::string> mapAddressBook;
141
142     CPubKey vchDefaultKey;
143     int64_t nTimeFirstKey;
144
145     const CWalletTx* GetWalletTx(const uint256& hash) const;
146
147     // check whether we are allowed to upgrade (or already support) to the named feature
148     bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
149
150     void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const;
151     void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
152     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;
153
154     // Simple select (without randomization)
155     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;
156
157     // keystore implementation
158     // Generate a new key
159     CPubKey GenerateNewKey();
160     CMalleableKeyView GenerateNewMalleableKey();
161     // Adds a key to the store, and saves it to disk.
162     bool AddKey(const CKey& key);
163     bool AddKey(const CMalleableKey& mKey);
164     // Adds a key to the store, without saving it to disk (used by LoadWallet)
165     bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
166     // Load metadata (used by LoadWallet)
167     bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
168     bool LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata);
169
170     // Load malleable key without saving it to disk (used by LoadWallet)
171     bool LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH) { return CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH); }
172     bool LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH) { return CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH); }
173
174     bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
175
176     // Adds an encrypted key to the store, and saves it to disk.
177     bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
178     bool AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH);
179     // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
180     bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
181     bool AddCScript(const CScript& redeemScript);
182     bool LoadCScript(const CScript& redeemScript);
183
184     // Adds a watch-only address to the store, and saves it to disk.
185     bool AddWatchOnly(const CScript &dest);
186     bool RemoveWatchOnly(const CScript &dest);
187     // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
188     bool LoadWatchOnly(const CScript &dest);
189
190     bool Unlock(const SecureString& strWalletPassphrase);
191     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
192     bool EncryptWallet(const SecureString& strWalletPassphrase);
193     bool DecryptWallet(const SecureString& strWalletPassphrase);
194
195     void GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const;
196     bool GetPEM(const CKeyID &keyID, const std::string &fileName, const SecureString &strPassPhrase) const;
197
198
199     /** Increment the next transaction order id
200         @return next transaction order id
201      */
202     int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
203
204     typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
205     typedef std::multimap<int64_t, TxPair > TxItems;
206
207     /** Get the wallet's activity log
208         @return multimap of ordered transactions and accounting entries
209         @warning Returned pointers are *only* valid within the scope of passed acentries
210      */
211     TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
212
213     void MarkDirty();
214     bool AddToWallet(const CWalletTx& wtxIn);
215     bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
216     bool EraseFromWallet(uint256 hash);
217     void ClearOrphans();
218     void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
219     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
220     int ScanForWalletTransaction(const uint256& hashTx);
221     void ReacceptWalletTransactions();
222     void ResendWalletTransactions(bool fForceResend=false);
223     int64_t GetBalance() const;
224     int64_t GetWatchOnlyBalance() const;
225     int64_t GetUnconfirmedBalance() const;
226     int64_t GetUnconfirmedWatchOnlyBalance() const;
227     int64_t GetImmatureBalance() const;
228     int64_t GetImmatureWatchOnlyBalance() const;
229     int64_t GetStake() const;
230     int64_t GetNewMint() const;
231     int64_t GetWatchOnlyStake() const;
232     int64_t GetWatchOnlyNewMint() const;
233     bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
234     bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
235     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
236
237     void GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight);
238     bool CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nTime, uint32_t nBits, CTransaction &txNew, CKey& key);
239     bool MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nMaxValue, std::list<uint256>& listMerged);
240
241     std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
242
243     bool NewKeyPool(unsigned int nSize = 0);
244     bool TopUpKeyPool(unsigned int nSize = 0);
245     int64_t AddReserveKey(const CKeyPool& keypool);
246     void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
247     void KeepKey(int64_t nIndex);
248     void ReturnKey(int64_t nIndex);
249     bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
250     int64_t GetOldestKeyPoolTime();
251     void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
252
253     std::set< std::set<CBitcoinAddress> > GetAddressGroupings();
254     std::map<CBitcoinAddress, int64_t> GetAddressBalances();
255
256     isminetype IsMine(const CTxIn& txin) const;
257     int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
258     isminetype IsMine(const CTxOut& txout) const;
259     int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const;
260     bool IsChange(const CTxOut& txout) const;
261     int64_t GetChange(const CTxOut& txout) const;
262     bool IsMine(const CTransaction& tx) const;
263     bool IsFromMe(const CTransaction& tx) const;
264     int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const;
265     int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const;
266     int64_t GetChange(const CTransaction& tx) const;
267     void SetBestChain(const CBlockLocator& loc);
268
269     DBErrors LoadWallet(bool& fFirstRunRet);
270     DBErrors ZapWalletTx();
271
272     bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
273     bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
274     bool DelAddressBookName(const CBitcoinAddress& address);
275     void UpdatedTransaction(const uint256 &hashTx);
276     void PrintWallet(const CBlock& block);
277
278     void Inventory(const uint256 &hash)
279     {
280         {
281             LOCK(cs_wallet);
282             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
283             if (mi != mapRequestCount.end())
284                 (*mi).second++;
285         }
286     }
287
288     unsigned int GetKeyPoolSize()
289     {
290         return (unsigned int)(setKeyPool.size());
291     }
292
293     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
294     bool SetDefaultKey(const CPubKey &vchPubKey);
295
296     // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
297     bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
298
299     // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
300     bool SetMaxVersion(int nVersion);
301
302     // get the current wallet format (the oldest client version guaranteed to understand this wallet)
303     int GetVersion() { return nWalletVersion; }
304
305     void FixSpentCoins(int& nMismatchSpent, int64_t& nBalanceInQuestion, bool fCheckOnly = false);
306     void DisableTransaction(const CTransaction &tx);
307
308     /** Address book entry changed.
309      * @note called with lock cs_wallet held.
310      */
311     boost::signals2::signal<void (CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
312
313     /** Wallet transaction added, removed or updated.
314      * @note called with lock cs_wallet held.
315      */
316     boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
317
318     /** Watch-only address added */
319     boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
320 };
321
322 /** A key allocated from the key pool. */
323 class CReserveKey
324 {
325 protected:
326     CWallet* pwallet;
327     int64_t nIndex;
328     CPubKey vchPubKey;
329 public:
330     CReserveKey(CWallet* pwalletIn)
331     {
332         nIndex = -1;
333         pwallet = pwalletIn;
334     }
335
336     ~CReserveKey()
337     {
338         if (!fShutdown)
339             ReturnKey();
340     }
341
342     void ReturnKey();
343     CPubKey GetReservedKey();
344     void KeepKey();
345 };
346
347
348 typedef std::map<std::string, std::string> mapValue_t;
349
350
351 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
352 {
353     if (!mapValue.count("n"))
354     {
355         nOrderPos = -1; // TODO: calculate elsewhere
356         return;
357     }
358     nOrderPos = atoi64(mapValue["n"].c_str());
359 }
360
361
362 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
363 {
364     if (nOrderPos == -1)
365         return;
366     mapValue["n"] = i64tostr(nOrderPos);
367 }
368
369
370 /** A transaction with a bunch of additional info that only the owner cares about.
371  * It includes any unrecorded transactions needed to link it back to the block chain.
372  */
373 class CWalletTx : public CMerkleTx
374 {
375 private:
376     const CWallet* pwallet;
377
378 public:
379     std::vector<CMerkleTx> vtxPrev;
380     mapValue_t mapValue;
381     std::vector<std::pair<std::string, std::string> > vOrderForm;
382     unsigned int fTimeReceivedIsTxTime;
383     unsigned int nTimeReceived;  // time received by this node
384     unsigned int nTimeSmart;
385     char fFromMe;
386     std::string strFromAccount;
387     std::vector<char> vfSpent; // which outputs are already spent
388     int64_t nOrderPos;  // position in ordered transaction list
389
390     // memory only
391     mutable bool fDebitCached;
392     mutable bool fWatchDebitCached;
393     mutable bool fCreditCached;
394     mutable bool fWatchCreditCached;
395     mutable bool fAvailableCreditCached;
396     mutable bool fImmatureCreditCached;
397     mutable bool fImmatureWatchCreditCached;
398     mutable bool fAvailableWatchCreditCached;
399     mutable bool fChangeCached;
400     mutable int64_t nDebitCached;
401     mutable int64_t nWatchDebitCached;
402     mutable int64_t nCreditCached;
403     mutable int64_t nWatchCreditCached;
404     mutable int64_t nAvailableCreditCached;
405     mutable int64_t nImmatureCreditCached;
406     mutable int64_t nImmatureWatchCreditCached;
407     mutable int64_t nAvailableWatchCreditCached;
408     mutable int64_t nChangeCached;
409
410     CWalletTx()
411     {
412         Init(NULL);
413     }
414
415     CWalletTx(const CWallet* pwalletIn)
416     {
417         Init(pwalletIn);
418     }
419
420     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
421     {
422         Init(pwalletIn);
423     }
424
425     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
426     {
427         Init(pwalletIn);
428     }
429
430     void Init(const CWallet* pwalletIn)
431     {
432         pwallet = pwalletIn;
433         vtxPrev.clear();
434         mapValue.clear();
435         vOrderForm.clear();
436         fTimeReceivedIsTxTime = false;
437         nTimeReceived = 0;
438         nTimeSmart = 0;
439         fFromMe = false;
440         strFromAccount.clear();
441         vfSpent.clear();
442         fDebitCached = false;
443         fWatchDebitCached = false;
444         fCreditCached = false;
445         fWatchCreditCached = false;
446         fAvailableCreditCached = false;
447         fAvailableWatchCreditCached = false;
448         fImmatureCreditCached = false;
449         fImmatureWatchCreditCached = false;
450         fChangeCached = false;
451         nDebitCached = 0;
452         nWatchDebitCached = 0;
453         nCreditCached = 0;
454         nWatchCreditCached = 0;
455         nAvailableCreditCached = 0;
456         nAvailableWatchCreditCached = 0;
457         nImmatureCreditCached = 0;
458         nImmatureWatchCreditCached = 0;
459         nChangeCached = 0;
460         nOrderPos = -1;
461     }
462
463     IMPLEMENT_SERIALIZE
464     (
465         CWalletTx* pthis = const_cast<CWalletTx*>(this);
466         if (fRead)
467             pthis->Init(NULL);
468         char fSpent = false;
469
470         if (!fRead)
471         {
472             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
473
474             std::string str;
475             BOOST_FOREACH(char f, vfSpent)
476             {
477                 str += (f ? '1' : '0');
478                 if (f)
479                     fSpent = true;
480             }
481             pthis->mapValue["spent"] = str;
482
483             WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
484
485             if (nTimeSmart)
486                 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
487         }
488
489         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
490         READWRITE(vtxPrev);
491         READWRITE(mapValue);
492         READWRITE(vOrderForm);
493         READWRITE(fTimeReceivedIsTxTime);
494         READWRITE(nTimeReceived);
495         READWRITE(fFromMe);
496         READWRITE(fSpent);
497
498         if (fRead)
499         {
500             pthis->strFromAccount = pthis->mapValue["fromaccount"];
501
502             if (mapValue.count("spent"))
503                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
504                     pthis->vfSpent.push_back(c != '0');
505             else
506                 pthis->vfSpent.assign(vout.size(), fSpent);
507
508             ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
509
510             pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
511         }
512
513         pthis->mapValue.erase("fromaccount");
514         pthis->mapValue.erase("version");
515         pthis->mapValue.erase("spent");
516         pthis->mapValue.erase("n");
517         pthis->mapValue.erase("timesmart");
518     )
519
520     // marks certain txout's as spent
521     // returns true if any update took place
522     bool UpdateSpent(const std::vector<char>& vfNewSpent)
523     {
524         bool fReturn = false;
525         for (unsigned int i = 0; i < vfNewSpent.size(); i++)
526         {
527             if (i == vfSpent.size())
528                 break;
529
530             if (vfNewSpent[i] && !vfSpent[i])
531             {
532                 vfSpent[i] = true;
533                 fReturn = true;
534                 fAvailableCreditCached = fAvailableWatchCreditCached = false;
535             }
536         }
537         return fReturn;
538     }
539
540     // make sure balances are recalculated
541     void MarkDirty()
542     {
543         fCreditCached = false;
544         fAvailableCreditCached = fAvailableWatchCreditCached = false;
545         fDebitCached = fWatchDebitCached = false;
546         fChangeCached = false;
547     }
548
549     void BindWallet(CWallet *pwalletIn)
550     {
551         pwallet = pwalletIn;
552         MarkDirty();
553     }
554
555     void MarkSpent(unsigned int nOut)
556     {
557         if (nOut >= vout.size())
558             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
559         vfSpent.resize(vout.size());
560         if (!vfSpent[nOut])
561         {
562             vfSpent[nOut] = true;
563             fAvailableCreditCached = fAvailableWatchCreditCached = false;
564         }
565     }
566
567     void MarkUnspent(unsigned int nOut)
568     {
569         if (nOut >= vout.size())
570             throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
571         vfSpent.resize(vout.size());
572         if (vfSpent[nOut])
573         {
574             vfSpent[nOut] = false;
575             fAvailableCreditCached = fAvailableWatchCreditCached = false;
576         }
577     }
578
579     bool IsSpent(unsigned int nOut) const
580     {
581         if (nOut >= vout.size())
582             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
583         if (nOut >= vfSpent.size())
584             return false;
585         return (!!vfSpent[nOut]);
586     }
587
588     int64_t GetDebit(const isminefilter& filter) const;
589     int64_t GetCredit(const isminefilter& filter) const;
590     int64_t GetImmatureCredit(bool fUseCache=true) const;
591     int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const;
592     int64_t GetAvailableCredit(bool fUseCache=true) const;
593     int64_t GetAvailableWatchCredit(bool fUseCache=true) const;
594     int64_t GetChange() const;
595
596     void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
597                     std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
598
599     void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
600                            int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
601
602     bool IsFromMe(const isminefilter& filter) const
603     {
604         return (GetDebit(filter) > 0);
605     }
606
607     bool InMempool() const;
608     bool IsTrusted() const;
609
610     bool WriteToDisk();
611
612     int64_t GetTxTime() const;
613     int GetRequestCount() const;
614
615     void AddSupportingTransactions(CTxDB& txdb);
616
617     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
618     bool AcceptWalletTransaction();
619
620     void RelayWalletTransaction(CTxDB& txdb);
621     void RelayWalletTransaction();
622 };
623
624
625
626
627 class COutput
628 {
629 public:
630     const CWalletTx *tx;
631     int i;
632     int nDepth;
633     bool fSpendable;
634
635     COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
636     {
637         tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
638     }
639
640     std::string ToString() const
641     {
642         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());
643     }
644 };
645
646
647
648
649 /** Private key that includes an expiration date in case it never gets used. */
650 class CWalletKey
651 {
652 public:
653     CPrivKey vchPrivKey;
654     int64_t nTimeCreated;
655     int64_t nTimeExpires;
656     std::string strComment;
657     //// todo: add something to note what created it (user, getnewaddress, change)
658     ////   maybe should have a map<string, string> property map
659
660     CWalletKey(int64_t nExpires=0)
661     {
662         nTimeCreated = (nExpires ? GetTime() : 0);
663         nTimeExpires = nExpires;
664     }
665
666     IMPLEMENT_SERIALIZE
667     (
668         if (!(nType & SER_GETHASH))
669             READWRITE(nVersion);
670         READWRITE(vchPrivKey);
671         READWRITE(nTimeCreated);
672         READWRITE(nTimeExpires);
673         READWRITE(strComment);
674     )
675 };
676
677
678
679
680
681
682 /** Account information.
683  * Stored in wallet with key "acc"+string account name.
684  */
685 class CAccount
686 {
687 public:
688     CPubKey vchPubKey;
689
690     CAccount()
691     {
692         SetNull();
693     }
694
695     void SetNull()
696     {
697         vchPubKey = CPubKey();
698     }
699
700     IMPLEMENT_SERIALIZE
701     (
702         if (!(nType & SER_GETHASH))
703             READWRITE(nVersion);
704         READWRITE(vchPubKey);
705     )
706 };
707
708
709
710 /** Internal transfers.
711  * Database key is acentry<account><counter>.
712  */
713 class CAccountingEntry
714 {
715 public:
716     std::string strAccount;
717     int64_t nCreditDebit;
718     int64_t nTime;
719     std::string strOtherAccount;
720     std::string strComment;
721     mapValue_t mapValue;
722     int64_t nOrderPos;  // position in ordered transaction list
723     uint64_t nEntryNo;
724
725     CAccountingEntry()
726     {
727         SetNull();
728     }
729
730     void SetNull()
731     {
732         nCreditDebit = 0;
733         nTime = 0;
734         strAccount.clear();
735         strOtherAccount.clear();
736         strComment.clear();
737         nOrderPos = -1;
738     }
739
740     IMPLEMENT_SERIALIZE
741     (
742         CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
743         if (!(nType & SER_GETHASH))
744             READWRITE(nVersion);
745         // Note: strAccount is serialized as part of the key, not here.
746         READWRITE(nCreditDebit);
747         READWRITE(nTime);
748         READWRITE(strOtherAccount);
749
750         if (!fRead)
751         {
752             WriteOrderPos(nOrderPos, me.mapValue);
753
754             if (!(mapValue.empty() && _ssExtra.empty()))
755             {
756                 CDataStream ss(nType, nVersion);
757                 ss.insert(ss.begin(), '\0');
758                 ss << mapValue;
759                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
760                 me.strComment.append(ss.str());
761             }
762         }
763
764         READWRITE(strComment);
765
766         size_t nSepPos = strComment.find("\0", 0, 1);
767         if (fRead)
768         {
769             me.mapValue.clear();
770             if (std::string::npos != nSepPos)
771             {
772                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
773                 ss >> me.mapValue;
774                 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
775             }
776             ReadOrderPos(me.nOrderPos, me.mapValue);
777         }
778         if (std::string::npos != nSepPos)
779             me.strComment.erase(nSepPos);
780
781         me.mapValue.erase("n");
782     )
783
784 private:
785     std::vector<char> _ssExtra;
786 };
787
788 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
789
790 #endif