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