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