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