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