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