f2d1fc020f76320c205556cf1090f05291619b45
[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     bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key);
199
200     std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
201     std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
202
203     bool NewKeyPool();
204     bool TopUpKeyPool(unsigned int nSize = 0);
205     int64 AddReserveKey(const CKeyPool& keypool);
206     void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
207     void KeepKey(int64 nIndex);
208     void ReturnKey(int64 nIndex);
209     bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
210     int64 GetOldestKeyPoolTime();
211     void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
212
213     std::set< std::set<CTxDestination> > GetAddressGroupings();
214     std::map<CTxDestination, int64> GetAddressBalances();
215
216     bool IsMine(const CTxIn& txin) const;
217     int64 GetDebit(const CTxIn& txin) const;
218     bool IsMine(const CTxOut& txout) const
219     {
220         return ::IsMine(*this, txout.scriptPubKey);
221     }
222     int64 GetCredit(const CTxOut& txout) const
223     {
224         if (!MoneyRange(txout.nValue))
225             throw std::runtime_error("CWallet::GetCredit() : value out of range");
226         return (IsMine(txout) ? txout.nValue : 0);
227     }
228     bool IsChange(const CTxOut& txout) const;
229     int64 GetChange(const CTxOut& txout) const
230     {
231         if (!MoneyRange(txout.nValue))
232             throw std::runtime_error("CWallet::GetChange() : value out of range");
233         return (IsChange(txout) ? txout.nValue : 0);
234     }
235     bool IsMine(const CTransaction& tx) const
236     {
237         BOOST_FOREACH(const CTxOut& txout, tx.vout)
238             if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
239                 return true;
240         return false;
241     }
242     bool IsFromMe(const CTransaction& tx) const
243     {
244         return (GetDebit(tx) > 0);
245     }
246     int64 GetDebit(const CTransaction& tx) const
247     {
248         int64 nDebit = 0;
249         BOOST_FOREACH(const CTxIn& txin, tx.vin)
250         {
251             nDebit += GetDebit(txin);
252             if (!MoneyRange(nDebit))
253                 throw std::runtime_error("CWallet::GetDebit() : value out of range");
254         }
255         return nDebit;
256     }
257     int64 GetCredit(const CTransaction& tx) const
258     {
259         int64 nCredit = 0;
260         BOOST_FOREACH(const CTxOut& txout, tx.vout)
261         {
262             nCredit += GetCredit(txout);
263             if (!MoneyRange(nCredit))
264                 throw std::runtime_error("CWallet::GetCredit() : value out of range");
265         }
266         return nCredit;
267     }
268     int64 GetChange(const CTransaction& tx) const
269     {
270         int64 nChange = 0;
271         BOOST_FOREACH(const CTxOut& txout, tx.vout)
272         {
273             nChange += GetChange(txout);
274             if (!MoneyRange(nChange))
275                 throw std::runtime_error("CWallet::GetChange() : value out of range");
276         }
277         return nChange;
278     }
279     void SetBestChain(const CBlockLocator& loc);
280
281     DBErrors LoadWallet(bool& fFirstRunRet);
282
283     DBErrors ZapWalletTx();
284
285     bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
286
287     bool DelAddressBookName(const CTxDestination& address);
288
289     void UpdatedTransaction(const uint256 &hashTx);
290
291     void PrintWallet(const CBlock& block);
292
293     void Inventory(const uint256 &hash)
294     {
295         {
296             LOCK(cs_wallet);
297             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
298             if (mi != mapRequestCount.end())
299                 (*mi).second++;
300         }
301     }
302
303     unsigned int GetKeyPoolSize()
304     {
305         return setKeyPool.size();
306     }
307
308     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
309
310     bool SetDefaultKey(const CPubKey &vchPubKey);
311
312     // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
313     bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
314
315     // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
316     bool SetMaxVersion(int nVersion);
317
318     // get the current wallet format (the oldest client version guaranteed to understand this wallet)
319     int GetVersion() { return nWalletVersion; }
320
321     // get wallet transactions that conflict with given transaction (spend same outputs)
322     std::set<uint256> GetConflicts(const uint256& txid) const;
323
324     void FixSpentCoins(int& nMismatchSpent, int64& nBalanceInQuestion, bool fCheckOnly = false);
325     void DisableTransaction(const CTransaction &tx);
326
327     /** Address book entry changed.
328      * @note called with lock cs_wallet held.
329      */
330     boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
331
332     /** Wallet transaction added, removed or updated.
333      * @note called with lock cs_wallet held.
334      */
335     boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
336 };
337
338 /** A key allocated from the key pool. */
339 class CReserveKey
340 {
341 protected:
342     CWallet* pwallet;
343     int64 nIndex;
344     CPubKey vchPubKey;
345 public:
346     CReserveKey(CWallet* pwalletIn)
347     {
348         nIndex = -1;
349         pwallet = pwalletIn;
350     }
351
352     ~CReserveKey()
353     {
354         if (!fShutdown)
355             ReturnKey();
356     }
357
358     void ReturnKey();
359     CPubKey GetReservedKey();
360     void KeepKey();
361 };
362
363
364 typedef std::map<std::string, std::string> mapValue_t;
365
366
367 static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
368 {
369     if (!mapValue.count("n"))
370     {
371         nOrderPos = -1; // TODO: calculate elsewhere
372         return;
373     }
374     nOrderPos = atoi64(mapValue["n"].c_str());
375 }
376
377
378 static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
379 {
380     if (nOrderPos == -1)
381         return;
382     mapValue["n"] = i64tostr(nOrderPos);
383 }
384
385
386 /** A transaction with a bunch of additional info that only the owner cares about.
387  * It includes any unrecorded transactions needed to link it back to the block chain.
388  */
389 class CWalletTx : public CMerkleTx
390 {
391 private:
392     const CWallet* pwallet;
393
394 public:
395     std::vector<CMerkleTx> vtxPrev;
396     mapValue_t mapValue;
397     std::vector<std::pair<std::string, std::string> > vOrderForm;
398     unsigned int fTimeReceivedIsTxTime;
399     unsigned int nTimeReceived;  // time received by this node
400     unsigned int nTimeSmart;
401     char fFromMe;
402     std::string strFromAccount;
403     std::vector<char> vfSpent; // which outputs are already spent
404     int64 nOrderPos;  // position in ordered transaction list
405
406     // memory only
407     mutable bool fDebitCached;
408     mutable bool fCreditCached;
409     mutable bool fAvailableCreditCached;
410     mutable bool fChangeCached;
411     mutable int64 nDebitCached;
412     mutable int64 nCreditCached;
413     mutable int64 nAvailableCreditCached;
414     mutable int64 nChangeCached;
415
416     CWalletTx()
417     {
418         Init(NULL);
419     }
420
421     CWalletTx(const CWallet* pwalletIn)
422     {
423         Init(pwalletIn);
424     }
425
426     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
427     {
428         Init(pwalletIn);
429     }
430
431     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
432     {
433         Init(pwalletIn);
434     }
435
436     void Init(const CWallet* pwalletIn)
437     {
438         pwallet = pwalletIn;
439         vtxPrev.clear();
440         mapValue.clear();
441         vOrderForm.clear();
442         fTimeReceivedIsTxTime = false;
443         nTimeReceived = 0;
444         nTimeSmart = 0;
445         fFromMe = false;
446         strFromAccount.clear();
447         vfSpent.clear();
448         fDebitCached = false;
449         fCreditCached = false;
450         fAvailableCreditCached = false;
451         fChangeCached = false;
452         nDebitCached = 0;
453         nCreditCached = 0;
454         nAvailableCreditCached = 0;
455         nChangeCached = 0;
456         nOrderPos = -1;
457     }
458
459     IMPLEMENT_SERIALIZE
460     (
461         CWalletTx* pthis = const_cast<CWalletTx*>(this);
462         if (fRead)
463             pthis->Init(NULL);
464         char fSpent = false;
465
466         if (!fRead)
467         {
468             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
469
470             std::string str;
471             BOOST_FOREACH(char f, vfSpent)
472             {
473                 str += (f ? '1' : '0');
474                 if (f)
475                     fSpent = true;
476             }
477             pthis->mapValue["spent"] = str;
478
479             WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
480
481             if (nTimeSmart)
482                 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
483         }
484
485         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
486         READWRITE(vtxPrev);
487         READWRITE(mapValue);
488         READWRITE(vOrderForm);
489         READWRITE(fTimeReceivedIsTxTime);
490         READWRITE(nTimeReceived);
491         READWRITE(fFromMe);
492         READWRITE(fSpent);
493
494         if (fRead)
495         {
496             pthis->strFromAccount = pthis->mapValue["fromaccount"];
497
498             if (mapValue.count("spent"))
499                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
500                     pthis->vfSpent.push_back(c != '0');
501             else
502                 pthis->vfSpent.assign(vout.size(), fSpent);
503
504             ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
505
506             pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
507         }
508
509         pthis->mapValue.erase("fromaccount");
510         pthis->mapValue.erase("version");
511         pthis->mapValue.erase("spent");
512         pthis->mapValue.erase("n");
513         pthis->mapValue.erase("timesmart");
514     )
515
516     // marks certain txout's as spent
517     // returns true if any update took place
518     bool UpdateSpent(const std::vector<char>& vfNewSpent)
519     {
520         bool fReturn = false;
521         for (unsigned int i = 0; i < vfNewSpent.size(); i++)
522         {
523             if (i == vfSpent.size())
524                 break;
525
526             if (vfNewSpent[i] && !vfSpent[i])
527             {
528                 vfSpent[i] = true;
529                 fReturn = true;
530                 fAvailableCreditCached = false;
531             }
532         }
533         return fReturn;
534     }
535
536     // make sure balances are recalculated
537     void MarkDirty()
538     {
539         fCreditCached = false;
540         fAvailableCreditCached = false;
541         fDebitCached = false;
542         fChangeCached = false;
543     }
544
545     void BindWallet(CWallet *pwalletIn)
546     {
547         pwallet = pwalletIn;
548         MarkDirty();
549     }
550
551     void MarkSpent(unsigned int nOut)
552     {
553         if (nOut >= vout.size())
554             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
555         vfSpent.resize(vout.size());
556         if (!vfSpent[nOut])
557         {
558             vfSpent[nOut] = true;
559             fAvailableCreditCached = false;
560         }
561     }
562
563     void MarkUnspent(unsigned int nOut)
564     {
565         if (nOut >= vout.size())
566             throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
567         vfSpent.resize(vout.size());
568         if (vfSpent[nOut])
569         {
570             vfSpent[nOut] = false;
571             fAvailableCreditCached = false;
572         }
573     }
574
575     bool IsSpent(unsigned int nOut) const
576     {
577         if (nOut >= vout.size())
578             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
579         if (nOut >= vfSpent.size())
580             return false;
581         return (!!vfSpent[nOut]);
582     }
583
584     int64 GetDebit() const
585     {
586         if (vin.empty())
587             return 0;
588         if (fDebitCached)
589             return nDebitCached;
590         nDebitCached = pwallet->GetDebit(*this);
591         fDebitCached = true;
592         return nDebitCached;
593     }
594
595     int64 GetCredit(bool fUseCache=true) const
596     {
597         // Must wait until coinbase is safely deep enough in the chain before valuing it
598         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
599             return 0;
600
601         // GetBalance can assume transactions in mapWallet won't change
602         if (fUseCache && fCreditCached)
603             return nCreditCached;
604         nCreditCached = pwallet->GetCredit(*this);
605         fCreditCached = true;
606         return nCreditCached;
607     }
608
609     int64 GetAvailableCredit(bool fUseCache=true) const
610     {
611         // Must wait until coinbase is safely deep enough in the chain before valuing it
612         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
613             return 0;
614
615         if (fUseCache && fAvailableCreditCached)
616             return nAvailableCreditCached;
617
618         int64 nCredit = 0;
619         for (unsigned int i = 0; i < vout.size(); i++)
620         {
621             if (!IsSpent(i))
622             {
623                 const CTxOut &txout = vout[i];
624                 nCredit += pwallet->GetCredit(txout);
625                 if (!MoneyRange(nCredit))
626                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
627             }
628         }
629
630         nAvailableCreditCached = nCredit;
631         fAvailableCreditCached = true;
632         return nCredit;
633     }
634
635
636     int64 GetChange() const
637     {
638         if (fChangeCached)
639             return nChangeCached;
640         nChangeCached = pwallet->GetChange(*this);
641         fChangeCached = true;
642         return nChangeCached;
643     }
644
645     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
646                     std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
647
648     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
649                            int64& nSent, int64& nFee) const;
650
651     bool IsFromMe() const
652     {
653         return (GetDebit() > 0);
654     }
655
656     bool IsTrusted() const
657     {
658         // Quick answer in most cases
659         if (!IsFinal())
660             return false;
661         int nDepth = GetDepthInMainChain();
662         if (nDepth >= 1)
663             return true;
664         if (nDepth < 0)
665             return false;
666         if (fConfChange || !IsFromMe()) // using wtx's cached debit
667             return false;
668
669         // If no confirmations but it's from us, we can still
670         // consider it confirmed if all dependencies are confirmed
671         std::map<uint256, const CMerkleTx*> mapPrev;
672         std::vector<const CMerkleTx*> vWorkQueue;
673         vWorkQueue.reserve(vtxPrev.size()+1);
674         vWorkQueue.push_back(this);
675         for (unsigned int i = 0; i < vWorkQueue.size(); i++)
676         {
677             const CMerkleTx* ptx = vWorkQueue[i];
678
679             if (!ptx->IsFinal())
680                 return false;
681             int nPDepth = ptx->GetDepthInMainChain();
682             if (nPDepth >= 1)
683                 continue;
684             if (nPDepth < 0)
685                 return false;
686             if (!pwallet->IsFromMe(*ptx))
687                 return false;
688
689             if (mapPrev.empty())
690             {
691                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
692                     mapPrev[tx.GetHash()] = &tx;
693             }
694
695             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
696             {
697                 if (!mapPrev.count(txin.prevout.hash))
698                     return false;
699                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
700             }
701         }
702         return true;
703     }
704
705     bool WriteToDisk();
706
707     int64 GetTxTime() const;
708     int GetRequestCount() const;
709
710     void AddSupportingTransactions();
711
712     bool AcceptWalletTransaction(bool fCheckInputs=true);
713     void RelayWalletTransaction();
714
715     std::set<uint256> GetConflicts() const;
716 };
717
718
719
720
721 class COutput
722 {
723 public:
724     const CWalletTx *tx;
725     int i;
726     int nDepth;
727
728     COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
729     {
730         tx = txIn; i = iIn; nDepth = nDepthIn;
731     }
732
733     std::string ToString() const
734     {
735         return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
736     }
737
738     void print() const
739     {
740         printf("%s\n", ToString().c_str());
741     }
742 };
743
744
745
746
747 /** Private key that includes an expiration date in case it never gets used. */
748 class CWalletKey
749 {
750 public:
751     CPrivKey vchPrivKey;
752     int64 nTimeCreated;
753     int64 nTimeExpires;
754     std::string strComment;
755     //// todo: add something to note what created it (user, getnewaddress, change)
756     ////   maybe should have a map<string, string> property map
757
758     CWalletKey(int64 nExpires=0)
759     {
760         nTimeCreated = (nExpires ? GetTime() : 0);
761         nTimeExpires = nExpires;
762     }
763
764     IMPLEMENT_SERIALIZE
765     (
766         if (!(nType & SER_GETHASH))
767             READWRITE(nVersion);
768         READWRITE(vchPrivKey);
769         READWRITE(nTimeCreated);
770         READWRITE(nTimeExpires);
771         READWRITE(strComment);
772     )
773 };
774
775
776
777
778
779
780 /** Account information.
781  * Stored in wallet with key "acc"+string account name.
782  */
783 class CAccount
784 {
785 public:
786     CPubKey vchPubKey;
787
788     CAccount()
789     {
790         SetNull();
791     }
792
793     void SetNull()
794     {
795         vchPubKey = CPubKey();
796     }
797
798     IMPLEMENT_SERIALIZE
799     (
800         if (!(nType & SER_GETHASH))
801             READWRITE(nVersion);
802         READWRITE(vchPubKey);
803     )
804 };
805
806
807
808 /** Internal transfers.
809  * Database key is acentry<account><counter>.
810  */
811 class CAccountingEntry
812 {
813 public:
814     std::string strAccount;
815     int64 nCreditDebit;
816     int64 nTime;
817     std::string strOtherAccount;
818     std::string strComment;
819     mapValue_t mapValue;
820     int64 nOrderPos;  // position in ordered transaction list
821     uint64 nEntryNo;
822
823     CAccountingEntry()
824     {
825         SetNull();
826     }
827
828     void SetNull()
829     {
830         nCreditDebit = 0;
831         nTime = 0;
832         strAccount.clear();
833         strOtherAccount.clear();
834         strComment.clear();
835         nOrderPos = -1;
836     }
837
838     IMPLEMENT_SERIALIZE
839     (
840         CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
841         if (!(nType & SER_GETHASH))
842             READWRITE(nVersion);
843         // Note: strAccount is serialized as part of the key, not here.
844         READWRITE(nCreditDebit);
845         READWRITE(nTime);
846         READWRITE(strOtherAccount);
847
848         if (!fRead)
849         {
850             WriteOrderPos(nOrderPos, me.mapValue);
851
852             if (!(mapValue.empty() && _ssExtra.empty()))
853             {
854                 CDataStream ss(nType, nVersion);
855                 ss.insert(ss.begin(), '\0');
856                 ss << mapValue;
857                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
858                 me.strComment.append(ss.str());
859             }
860         }
861
862         READWRITE(strComment);
863
864         size_t nSepPos = strComment.find("\0", 0, 1);
865         if (fRead)
866         {
867             me.mapValue.clear();
868             if (std::string::npos != nSepPos)
869             {
870                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
871                 ss >> me.mapValue;
872                 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
873             }
874             ReadOrderPos(me.nOrderPos, me.mapValue);
875         }
876         if (std::string::npos != nSepPos)
877             me.strComment.erase(nSepPos);
878
879         me.mapValue.erase("n");
880     )
881
882 private:
883     std::vector<char> _ssExtra;
884 };
885
886 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
887
888 #endif