Bump version to 0.5.8
[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 #include "base58.h"
21
22 extern unsigned int nStakeMaxAge;
23 extern bool fWalletUnlockMintOnly;
24 extern bool fConfChange;
25 class CAccountingEntry;
26 class CWalletTx;
27 class CReserveKey;
28 class COutput;
29 class CCoinControl;
30
31 // Set of selected transactions
32 typedef std::set<std::pair<const CWalletTx*,unsigned int> > CoinsSet;
33
34 /** (client) version numbers for particular wallet features */
35 enum WalletFeature
36 {
37     FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
38
39     FEATURE_WALLETCRYPT = 40000, // wallet encryption
40     FEATURE_COMPRPUBKEY = 60000, // compressed public keys
41     FEATURE_MALLKEY = 60017,
42     FEATURE_LATEST = 60017
43 };
44
45 /** A key pool entry */
46 class CKeyPool
47 {
48 public:
49     int64_t nTime;
50     CPubKey vchPubKey;
51
52     CKeyPool()
53     {
54         nTime = GetTime();
55     }
56
57     CKeyPool(const CPubKey& vchPubKeyIn)
58     {
59         nTime = GetTime();
60         vchPubKey = vchPubKeyIn;
61     }
62
63     IMPLEMENT_SERIALIZE
64     (
65         if (!(nType & SER_GETHASH))
66             READWRITE(nVersion);
67         READWRITE(nTime);
68         READWRITE(vchPubKey);
69     )
70 };
71
72 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
73  * and provides the ability to create new transactions.
74  */
75 class CWallet : public CCryptoKeyStore
76 {
77 private:
78     bool SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl *coinControl=NULL) const;
79
80     CWalletDB *pwalletdbEncryption, *pwalletdbDecryption;
81
82     // the current wallet version: clients below this version are not able to load the wallet
83     int nWalletVersion;
84
85     // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
86     int nWalletMaxVersion;
87
88     int64_t nNextResend;
89     int64_t nLastResend;
90
91     // stake mining statistics
92     uint64_t nKernelsTried;
93     uint64_t nCoinDaysTried;
94
95 public:
96     mutable CCriticalSection cs_wallet;
97
98     bool fFileBacked;
99     std::string strWalletFile;
100
101     std::set<int64_t> setKeyPool;
102     /*
103     std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
104     std::map<CMalleableKeyView, CKeyMetadata> mapMalleableKeyMetadata;
105     */
106
107     std::map<CBitcoinAddress, CKeyMetadata> mapKeyMetadata;
108
109     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
110     MasterKeyMap mapMasterKeys;
111     unsigned int nMasterKeyMaxID;
112
113     CWallet()
114     {
115         SetNull();
116     }
117     CWallet(std::string strWalletFileIn)
118     {
119         SetNull();
120
121         strWalletFile = strWalletFileIn;
122         fFileBacked = true;
123     }
124     void SetNull()
125     {
126         nWalletVersion = FEATURE_BASE;
127         nWalletMaxVersion = FEATURE_BASE;
128         fFileBacked = false;
129         nMasterKeyMaxID = 0;
130         pwalletdbEncryption = NULL;
131         pwalletdbDecryption = NULL;
132         nNextResend = 0;
133         nLastResend = 0;
134         nOrderPosNext = 0;
135         nKernelsTried = 0;
136         nCoinDaysTried = 0;
137         nTimeFirstKey = 0;
138     }
139
140     std::map<uint256, CWalletTx> mapWallet;
141     std::vector<uint256> vMintingWalletUpdated;
142     int64_t nOrderPosNext;
143     std::map<uint256, int> mapRequestCount;
144
145     std::map<CBitcoinAddress, std::string> mapAddressBook;
146
147     CPubKey vchDefaultKey;
148     int64_t nTimeFirstKey;
149
150     const CWalletTx* GetWalletTx(const uint256& hash) const;
151
152     // check whether we are allowed to upgrade (or already support) to the named feature
153     bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
154
155     void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const;
156     void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
157     bool SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
158
159     // Simple select (without randomization)
160     bool SelectCoinsSimple(int64_t nTargetValue, int64_t nMinValue, int64_t nMaxValue, unsigned int nSpendTime, int nMinConf, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
161
162     // keystore implementation
163     // Generate a new key
164     CPubKey GenerateNewKey();
165     CMalleableKeyView GenerateNewMalleableKey();
166     // Adds a key to the store, and saves it to disk.
167     bool AddKey(const CKey& key);
168     bool AddKey(const CMalleableKey& mKey);
169     // Adds a key to the store, without saving it to disk (used by LoadWallet)
170     bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
171     // Load metadata (used by LoadWallet)
172     bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
173     bool LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata);
174
175     // Load malleable key without saving it to disk (used by LoadWallet)
176     bool LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH) { return CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH); }
177     bool LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH) { return CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH); }
178
179     bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
180
181     // Adds an encrypted key to the store, and saves it to disk.
182     bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
183     bool AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH);
184     // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
185     bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
186     bool AddCScript(const CScript& redeemScript);
187     bool LoadCScript(const CScript& redeemScript);
188
189     // Adds a watch-only address to the store, and saves it to disk.
190     bool AddWatchOnly(const CScript &dest);
191     bool RemoveWatchOnly(const CScript &dest);
192     // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
193     bool LoadWatchOnly(const CScript &dest);
194
195     bool Unlock(const SecureString& strWalletPassphrase);
196     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
197     bool EncryptWallet(const SecureString& strWalletPassphrase);
198     bool DecryptWallet(const SecureString& strWalletPassphrase);
199
200     void GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const;
201     bool GetPEM(const CKeyID &keyID, const std::string &fileName, const SecureString &strPassPhrase) const;
202
203
204     /** Increment the next transaction order id
205         @return next transaction order id
206      */
207     int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
208
209     typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
210     typedef std::multimap<int64_t, TxPair > TxItems;
211
212     /** Get the wallet's activity log
213         @return multimap of ordered transactions and accounting entries
214         @warning Returned pointers are *only* valid within the scope of passed acentries
215      */
216     TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
217
218     void MarkDirty();
219     bool AddToWallet(const CWalletTx& wtxIn);
220     bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
221     bool EraseFromWallet(uint256 hash);
222     void ClearOrphans();
223     void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
224     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
225     int ScanForWalletTransaction(const uint256& hashTx);
226     void ReacceptWalletTransactions();
227     void ResendWalletTransactions(int64_t nBestBlockTime);
228     std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
229     int64_t GetBalance() const;
230     int64_t GetWatchOnlyBalance() const;
231     int64_t GetUnconfirmedBalance() const;
232     int64_t GetUnconfirmedWatchOnlyBalance() const;
233     int64_t GetImmatureBalance() const;
234     int64_t GetImmatureWatchOnlyBalance() const;
235     int64_t GetStake() const;
236     int64_t GetNewMint() const;
237     int64_t GetWatchOnlyStake() const;
238     int64_t GetWatchOnlyNewMint() const;
239     bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
240     bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
241     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
242
243     void GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight);
244     bool CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nTime, uint32_t nBits, CTransaction &txNew, CKey& key);
245     bool MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nMaxValue, std::list<uint256>& listMerged);
246
247     std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
248
249     bool NewKeyPool(unsigned int nSize = 0);
250     bool TopUpKeyPool(unsigned int nSize = 0);
251     int64_t AddReserveKey(const CKeyPool& keypool);
252     void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
253     void KeepKey(int64_t nIndex);
254     void ReturnKey(int64_t nIndex);
255     bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
256     int64_t GetOldestKeyPoolTime();
257     void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
258
259     std::set< std::set<CBitcoinAddress> > GetAddressGroupings();
260     std::map<CBitcoinAddress, int64_t> GetAddressBalances();
261
262     isminetype IsMine(const CTxIn& txin) const;
263     int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
264     isminetype IsMine(const CTxOut& txout) const;
265     int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const;
266     bool IsChange(const CTxOut& txout) const;
267     int64_t GetChange(const CTxOut& txout) const;
268     bool IsMine(const CTransaction& tx) const;
269     bool IsFromMe(const CTransaction& tx) const;
270     int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const;
271     int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const;
272     int64_t GetChange(const CTransaction& tx) const;
273     void SetBestChain(const CBlockLocator& loc);
274
275     DBErrors LoadWallet(bool& fFirstRunRet);
276     DBErrors ZapWalletTx();
277
278     bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
279     bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
280     bool DelAddressBookName(const CBitcoinAddress& address);
281     void UpdatedTransaction(const uint256 &hashTx);
282     void PrintWallet(const CBlock& block);
283
284     void Inventory(const uint256 &hash)
285     {
286         {
287             LOCK(cs_wallet);
288             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
289             if (mi != mapRequestCount.end())
290                 (*mi).second++;
291         }
292     }
293
294     unsigned int GetKeyPoolSize()
295     {
296         return (unsigned int)(setKeyPool.size());
297     }
298
299     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
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_t& 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 CBitcoinAddress &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     /** Watch-only address added */
325     boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
326 };
327
328 /** A key allocated from the key pool. */
329 class CReserveKey
330 {
331 protected:
332     CWallet* pwallet;
333     int64_t nIndex;
334     CPubKey vchPubKey;
335 public:
336     CReserveKey(CWallet* pwalletIn)
337     {
338         nIndex = -1;
339         pwallet = pwalletIn;
340     }
341
342     ~CReserveKey()
343     {
344         if (!fShutdown)
345             ReturnKey();
346     }
347
348     void ReturnKey();
349     CPubKey GetReservedKey();
350     void KeepKey();
351 };
352
353
354 typedef std::map<std::string, std::string> mapValue_t;
355
356
357 static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
358 {
359     if (!mapValue.count("n"))
360     {
361         nOrderPos = -1; // TODO: calculate elsewhere
362         return;
363     }
364     nOrderPos = atoi64(mapValue["n"].c_str());
365 }
366
367
368 static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
369 {
370     if (nOrderPos == -1)
371         return;
372     mapValue["n"] = i64tostr(nOrderPos);
373 }
374
375
376 /** A transaction with a bunch of additional info that only the owner cares about.
377  * It includes any unrecorded transactions needed to link it back to the block chain.
378  */
379 class CWalletTx : public CMerkleTx
380 {
381 private:
382     const CWallet* pwallet;
383
384 public:
385     std::vector<CMerkleTx> vtxPrev;
386     mapValue_t mapValue;
387     std::vector<std::pair<std::string, std::string> > vOrderForm;
388     unsigned int fTimeReceivedIsTxTime;
389     unsigned int nTimeReceived;  // time received by this node
390     unsigned int nTimeSmart;
391     char fFromMe;
392     std::string strFromAccount;
393     std::vector<char> vfSpent; // which outputs are already spent
394     int64_t nOrderPos;  // position in ordered transaction list
395
396     // memory only
397     mutable bool fDebitCached;
398     mutable bool fWatchDebitCached;
399     mutable bool fCreditCached;
400     mutable bool fWatchCreditCached;
401     mutable bool fAvailableCreditCached;
402     mutable bool fImmatureCreditCached;
403     mutable bool fImmatureWatchCreditCached;
404     mutable bool fAvailableWatchCreditCached;
405     mutable bool fChangeCached;
406     mutable int64_t nDebitCached;
407     mutable int64_t nWatchDebitCached;
408     mutable int64_t nCreditCached;
409     mutable int64_t nWatchCreditCached;
410     mutable int64_t nAvailableCreditCached;
411     mutable int64_t nImmatureCreditCached;
412     mutable int64_t nImmatureWatchCreditCached;
413     mutable int64_t nAvailableWatchCreditCached;
414     mutable int64_t nChangeCached;
415
416     CWalletTx()
417     {
418         Init(NULL);
419     }
420
421     CWalletTx(const CWallet* pwalletIn)
422     {
423         Init(pwalletIn);
424     }
425
426     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
427     {
428         Init(pwalletIn);
429     }
430
431     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
432     {
433         Init(pwalletIn);
434     }
435
436     void Init(const CWallet* pwalletIn)
437     {
438         pwallet = pwalletIn;
439         vtxPrev.clear();
440         mapValue.clear();
441         vOrderForm.clear();
442         fTimeReceivedIsTxTime = false;
443         nTimeReceived = 0;
444         nTimeSmart = 0;
445         fFromMe = false;
446         strFromAccount.clear();
447         vfSpent.clear();
448         fDebitCached = false;
449         fWatchDebitCached = false;
450         fCreditCached = false;
451         fWatchCreditCached = false;
452         fAvailableCreditCached = false;
453         fAvailableWatchCreditCached = false;
454         fImmatureCreditCached = false;
455         fImmatureWatchCreditCached = false;
456         fChangeCached = false;
457         nDebitCached = 0;
458         nWatchDebitCached = 0;
459         nCreditCached = 0;
460         nWatchCreditCached = 0;
461         nAvailableCreditCached = 0;
462         nAvailableWatchCreditCached = 0;
463         nImmatureCreditCached = 0;
464         nImmatureWatchCreditCached = 0;
465         nChangeCached = 0;
466         nOrderPos = -1;
467     }
468
469     IMPLEMENT_SERIALIZE
470     (
471         CWalletTx* pthis = const_cast<CWalletTx*>(this);
472         if (fRead)
473             pthis->Init(NULL);
474         char fSpent = false;
475
476         if (!fRead)
477         {
478             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
479
480             std::string str;
481             BOOST_FOREACH(char f, vfSpent)
482             {
483                 str += (f ? '1' : '0');
484                 if (f)
485                     fSpent = true;
486             }
487             pthis->mapValue["spent"] = str;
488
489             WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
490
491             if (nTimeSmart)
492                 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
493         }
494
495         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
496         READWRITE(vtxPrev);
497         READWRITE(mapValue);
498         READWRITE(vOrderForm);
499         READWRITE(fTimeReceivedIsTxTime);
500         READWRITE(nTimeReceived);
501         READWRITE(fFromMe);
502         READWRITE(fSpent);
503
504         if (fRead)
505         {
506             pthis->strFromAccount = pthis->mapValue["fromaccount"];
507
508             if (mapValue.count("spent"))
509                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
510                     pthis->vfSpent.push_back(c != '0');
511             else
512                 pthis->vfSpent.assign(vout.size(), fSpent);
513
514             ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
515
516             pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
517         }
518
519         pthis->mapValue.erase("fromaccount");
520         pthis->mapValue.erase("version");
521         pthis->mapValue.erase("spent");
522         pthis->mapValue.erase("n");
523         pthis->mapValue.erase("timesmart");
524     )
525
526     // marks certain txout's as spent
527     // returns true if any update took place
528     bool UpdateSpent(const std::vector<char>& vfNewSpent);
529
530     // make sure balances are recalculated
531     void MarkDirty();
532     void BindWallet(CWallet *pwalletIn);
533     void MarkSpent(unsigned int nOut);
534     void MarkUnspent(unsigned int nOut);
535     bool IsSpent(unsigned int nOut) const;
536
537     int64_t GetDebit(const isminefilter& filter) const;
538     int64_t GetCredit(const isminefilter& filter) const;
539     int64_t GetImmatureCredit(bool fUseCache=true) const;
540     int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const;
541     int64_t GetAvailableCredit(bool fUseCache=true) const;
542     int64_t GetAvailableWatchCredit(bool fUseCache=true) const;
543     int64_t GetChange() const;
544
545     void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
546                     std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
547
548     void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
549                            int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
550
551     bool IsFromMe(const isminefilter& filter) const
552     {
553         return (GetDebit(filter) > 0);
554     }
555
556     bool InMempool() const;
557     bool IsTrusted() const;
558
559     bool WriteToDisk();
560
561     int64_t GetTxTime() const;
562     int GetRequestCount() const;
563
564     void AddSupportingTransactions(CTxDB& txdb);
565
566     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
567     bool AcceptWalletTransaction();
568
569     bool RelayWalletTransaction(CTxDB& txdb);
570     bool RelayWalletTransaction();
571 };
572
573
574
575
576 class COutput
577 {
578 public:
579     const CWalletTx *tx;
580     int i;
581     int nDepth;
582     bool fSpendable;
583
584     COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
585     {
586         tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
587     }
588
589     std::string ToString() const
590     {
591         return strprintf("COutput(%s, %d, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, fSpendable, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
592     }
593 };
594
595
596
597
598 /** Private key that includes an expiration date in case it never gets used. */
599 class CWalletKey
600 {
601 public:
602     CPrivKey vchPrivKey;
603     int64_t nTimeCreated;
604     int64_t nTimeExpires;
605     std::string strComment;
606     //// todo: add something to note what created it (user, getnewaddress, change)
607     ////   maybe should have a map<string, string> property map
608
609     CWalletKey(int64_t nExpires=0)
610     {
611         nTimeCreated = (nExpires ? GetTime() : 0);
612         nTimeExpires = nExpires;
613     }
614
615     IMPLEMENT_SERIALIZE
616     (
617         if (!(nType & SER_GETHASH))
618             READWRITE(nVersion);
619         READWRITE(vchPrivKey);
620         READWRITE(nTimeCreated);
621         READWRITE(nTimeExpires);
622         READWRITE(strComment);
623     )
624 };
625
626
627
628
629
630
631 /** Account information.
632  * Stored in wallet with key "acc"+string account name.
633  */
634 class CAccount
635 {
636 public:
637     CPubKey vchPubKey;
638
639     CAccount()
640     {
641         SetNull();
642     }
643
644     void SetNull()
645     {
646         vchPubKey = CPubKey();
647     }
648
649     IMPLEMENT_SERIALIZE
650     (
651         if (!(nType & SER_GETHASH))
652             READWRITE(nVersion);
653         READWRITE(vchPubKey);
654     )
655 };
656
657
658
659 /** Internal transfers.
660  * Database key is acentry<account><counter>.
661  */
662 class CAccountingEntry
663 {
664 public:
665     std::string strAccount;
666     int64_t nCreditDebit;
667     int64_t nTime;
668     std::string strOtherAccount;
669     std::string strComment;
670     mapValue_t mapValue;
671     int64_t nOrderPos;  // position in ordered transaction list
672     uint64_t nEntryNo;
673
674     CAccountingEntry()
675     {
676         SetNull();
677     }
678
679     void SetNull()
680     {
681         nCreditDebit = 0;
682         nTime = 0;
683         strAccount.clear();
684         strOtherAccount.clear();
685         strComment.clear();
686         nOrderPos = -1;
687     }
688
689     IMPLEMENT_SERIALIZE
690     (
691         CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
692         if (!(nType & SER_GETHASH))
693             READWRITE(nVersion);
694         // Note: strAccount is serialized as part of the key, not here.
695         READWRITE(nCreditDebit);
696         READWRITE(nTime);
697         READWRITE(strOtherAccount);
698
699         if (!fRead)
700         {
701             WriteOrderPos(nOrderPos, me.mapValue);
702
703             if (!(mapValue.empty() && _ssExtra.empty()))
704             {
705                 CDataStream ss(nType, nVersion);
706                 ss.insert(ss.begin(), '\0');
707                 ss << mapValue;
708                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
709                 me.strComment.append(ss.str());
710             }
711         }
712
713         READWRITE(strComment);
714
715         size_t nSepPos = strComment.find("\0", 0, 1);
716         if (fRead)
717         {
718             me.mapValue.clear();
719             if (std::string::npos != nSepPos)
720             {
721                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
722                 ss >> me.mapValue;
723                 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
724             }
725             ReadOrderPos(me.nOrderPos, me.mapValue);
726         }
727         if (std::string::npos != nSepPos)
728             me.strComment.erase(nSepPos);
729
730         me.mapValue.erase("n");
731     )
732
733 private:
734     std::vector<char> _ssExtra;
735 };
736
737 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
738
739 #endif