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