OSDN Git Service

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