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