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