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