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