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