Improve getmininginfo
[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
98
99     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
100     MasterKeyMap mapMasterKeys;
101     unsigned int nMasterKeyMaxID;
102
103     CWallet()
104     {
105         nWalletVersion = FEATURE_BASE;
106         nWalletMaxVersion = FEATURE_BASE;
107         fFileBacked = false;
108         nMasterKeyMaxID = 0;
109         pwalletdbEncryption = NULL;
110         nOrderPosNext = 0;
111     }
112     CWallet(std::string strWalletFileIn)
113     {
114         nWalletVersion = FEATURE_BASE;
115         nWalletMaxVersion = FEATURE_BASE;
116         strWalletFile = strWalletFileIn;
117         fFileBacked = true;
118         nMasterKeyMaxID = 0;
119         pwalletdbEncryption = NULL;
120         nOrderPosNext = 0;
121     }
122
123     std::map<uint256, CWalletTx> mapWallet;
124     int64 nOrderPosNext;
125     std::map<uint256, int> mapRequestCount;
126
127     std::map<CTxDestination, std::string> mapAddressBook;
128
129     CPubKey vchDefaultKey;
130
131     // check whether we are allowed to upgrade (or already support) to the named feature
132     bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
133
134     void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true) const;
135     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;
136     // keystore implementation
137     // Generate a new key
138     CPubKey GenerateNewKey();
139     // Adds a key to the store, and saves it to disk.
140     bool AddKey(const CKey& key);
141     // Adds a key to the store, without saving it to disk (used by LoadWallet)
142     bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
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     /** Increment the next transaction order id
158         @return next transaction order id
159      */
160     int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
161
162     typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
163     typedef std::multimap<int64, TxPair > TxItems;
164
165     /** Get the wallet's activity log
166         @return multimap of ordered transactions and accounting entries
167         @warning Returned pointers are *only* valid within the scope of passed acentries
168      */
169     TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
170
171     void MarkDirty();
172     bool AddToWallet(const CWalletTx& wtxIn);
173     bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
174     bool EraseFromWallet(uint256 hash);
175     void WalletUpdateSpent(const CTransaction& prevout);
176     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
177     int ScanForWalletTransaction(const uint256& hashTx);
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);
186     bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
187     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
188
189     uint64 GetStakeMintPower(const CKeyStore& keystore, enum StakeWeightMode mode=STAKE_NORMAL);
190     bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew);
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();
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);
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))
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     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(CTxDB& txdb);
692
693     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
694     bool AcceptWalletTransaction();
695
696     void RelayWalletTransaction(CTxDB& txdb);
697     void RelayWalletTransaction();
698 };
699
700
701
702
703 class COutput
704 {
705 public:
706     const CWalletTx *tx;
707     int i;
708     int nDepth;
709
710     COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
711     {
712         tx = txIn; i = iIn; nDepth = nDepthIn;
713     }
714
715     std::string ToString() const
716     {
717         return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
718     }
719
720     void print() const
721     {
722         printf("%s\n", ToString().c_str());
723     }
724 };
725
726
727
728
729 /** Private key that includes an expiration date in case it never gets used. */
730 class CWalletKey
731 {
732 public:
733     CPrivKey vchPrivKey;
734     int64 nTimeCreated;
735     int64 nTimeExpires;
736     std::string strComment;
737     //// todo: add something to note what created it (user, getnewaddress, change)
738     ////   maybe should have a map<string, string> property map
739
740     CWalletKey(int64 nExpires=0)
741     {
742         nTimeCreated = (nExpires ? GetTime() : 0);
743         nTimeExpires = nExpires;
744     }
745
746     IMPLEMENT_SERIALIZE
747     (
748         if (!(nType & SER_GETHASH))
749             READWRITE(nVersion);
750         READWRITE(vchPrivKey);
751         READWRITE(nTimeCreated);
752         READWRITE(nTimeExpires);
753         READWRITE(strComment);
754     )
755 };
756
757
758
759
760
761
762 /** Account information.
763  * Stored in wallet with key "acc"+string account name.
764  */
765 class CAccount
766 {
767 public:
768     CPubKey vchPubKey;
769
770     CAccount()
771     {
772         SetNull();
773     }
774
775     void SetNull()
776     {
777         vchPubKey = CPubKey();
778     }
779
780     IMPLEMENT_SERIALIZE
781     (
782         if (!(nType & SER_GETHASH))
783             READWRITE(nVersion);
784         READWRITE(vchPubKey);
785     )
786 };
787
788
789
790 /** Internal transfers.
791  * Database key is acentry<account><counter>.
792  */
793 class CAccountingEntry
794 {
795 public:
796     std::string strAccount;
797     int64 nCreditDebit;
798     int64 nTime;
799     std::string strOtherAccount;
800     std::string strComment;
801     mapValue_t mapValue;
802     int64 nOrderPos;  // position in ordered transaction list
803     uint64 nEntryNo;
804
805     CAccountingEntry()
806     {
807         SetNull();
808     }
809
810     void SetNull()
811     {
812         nCreditDebit = 0;
813         nTime = 0;
814         strAccount.clear();
815         strOtherAccount.clear();
816         strComment.clear();
817         nOrderPos = -1;
818     }
819
820     IMPLEMENT_SERIALIZE
821     (
822         CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
823         if (!(nType & SER_GETHASH))
824             READWRITE(nVersion);
825         // Note: strAccount is serialized as part of the key, not here.
826         READWRITE(nCreditDebit);
827         READWRITE(nTime);
828         READWRITE(strOtherAccount);
829
830         if (!fRead)
831         {
832             WriteOrderPos(nOrderPos, me.mapValue);
833
834             if (!(mapValue.empty() && _ssExtra.empty()))
835             {
836                 CDataStream ss(nType, nVersion);
837                 ss.insert(ss.begin(), '\0');
838                 ss << mapValue;
839                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
840                 me.strComment.append(ss.str());
841             }
842         }
843
844         READWRITE(strComment);
845
846         size_t nSepPos = strComment.find("\0", 0, 1);
847         if (fRead)
848         {
849             me.mapValue.clear();
850             if (std::string::npos != nSepPos)
851             {
852                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
853                 ss >> me.mapValue;
854                 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
855             }
856             ReadOrderPos(me.nOrderPos, me.mapValue);
857         }
858         if (std::string::npos != nSepPos)
859             me.strComment.erase(nSepPos);
860
861         me.mapValue.erase("n");
862     )
863
864 private:
865     std::vector<char> _ssExtra;
866 };
867
868 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
869
870 #endif