Use standard C99 (and Qt) types for 64-bit integers
[novacoin.git] / src / wallet.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_WALLET_H
6 #define BITCOIN_WALLET_H
7
8 #include <stdint.h>
9
10 #include "bignum.h"
11 #include "key.h"
12 #include "keystore.h"
13 #include "script.h"
14
15 class CWalletTx;
16 class CReserveKey;
17 class CWalletDB;
18
19 // A CWallet is an extension of a keystore, which also maintains a set of
20 // transactions and balances, and provides the ability to create new
21 // transactions
22 class CWallet : public CCryptoKeyStore
23 {
24 private:
25     bool SelectCoinsMinConf(int64_t nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
26     bool SelectCoins(int64_t nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const;
27
28     CWalletDB *pwalletdbEncryption;
29
30 public:
31     mutable CCriticalSection cs_wallet;
32
33     bool fFileBacked;
34     std::string strWalletFile;
35
36     std::set<int64_t> setKeyPool;
37
38     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
39     MasterKeyMap mapMasterKeys;
40     unsigned int nMasterKeyMaxID;
41
42     CWallet()
43     {
44         fFileBacked = false;
45         nMasterKeyMaxID = 0;
46         pwalletdbEncryption = NULL;
47     }
48     CWallet(std::string strWalletFileIn)
49     {
50         strWalletFile = strWalletFileIn;
51         fFileBacked = true;
52         nMasterKeyMaxID = 0;
53         pwalletdbEncryption = NULL;
54     }
55
56     std::map<uint256, CWalletTx> mapWallet;
57     std::vector<uint256> vWalletUpdated;
58
59     std::map<uint256, int> mapRequestCount;
60
61     std::map<CBitcoinAddress, std::string> mapAddressBook;
62
63     std::vector<unsigned char> vchDefaultKey;
64
65     // keystore implementation
66     // Adds a key to the store, and saves it to disk.
67     bool AddKey(const CKey& key);
68     // Adds a key to the store, without saving it to disk (used by LoadWallet)
69     bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
70
71     // Adds an encrypted key to the store, and saves it to disk.
72     bool AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
73     // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
74     bool LoadCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
75     bool AddCScript(const uint160& hash, const CScript& redeemScript);
76     bool LoadCScript(const uint160& hash, const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(hash, redeemScript); }
77
78     bool Unlock(const SecureString& strWalletPassphrase);
79     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
80     bool EncryptWallet(const SecureString& strWalletPassphrase);
81
82     void MarkDirty();
83     bool AddToWallet(const CWalletTx& wtxIn);
84     bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
85     bool EraseFromWallet(uint256 hash);
86     void WalletUpdateSpent(const CTransaction& prevout);
87     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
88     int ScanForWalletTransaction(const uint256& hashTx);
89     void ReacceptWalletTransactions();
90     void ResendWalletTransactions();
91     int64_t GetBalance() const;
92     int64_t GetUnconfirmedBalance() const;
93     bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet);
94     bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet);
95     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
96     bool BroadcastTransaction(CWalletTx& wtxNew);
97     std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
98     std::string SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
99
100     bool NewKeyPool();
101     bool TopUpKeyPool();
102     int64_t AddReserveKey(const CKeyPool& keypool);
103     void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
104     void KeepKey(int64_t nIndex);
105     void ReturnKey(int64_t nIndex);
106     bool GetKeyFromPool(std::vector<unsigned char> &key, bool fAllowReuse=true);
107     int64_t GetOldestKeyPoolTime();
108     void GetAllReserveAddresses(std::set<CBitcoinAddress>& setAddress);
109
110     bool IsMine(const CTxIn& txin) const;
111     int64_t GetDebit(const CTxIn& txin) const;
112     bool IsMine(const CTxOut& txout) const
113     {
114         return ::IsMine(*this, txout.scriptPubKey);
115     }
116     int64_t GetCredit(const CTxOut& txout) const
117     {
118         if (!MoneyRange(txout.nValue))
119             throw std::runtime_error("CWallet::GetCredit() : value out of range");
120         return (IsMine(txout) ? txout.nValue : 0);
121     }
122     bool IsChange(const CTxOut& txout) const;
123     int64_t GetChange(const CTxOut& txout) const
124     {
125         if (!MoneyRange(txout.nValue))
126             throw std::runtime_error("CWallet::GetChange() : value out of range");
127         return (IsChange(txout) ? txout.nValue : 0);
128     }
129     bool IsMine(const CTransaction& tx) const
130     {
131         BOOST_FOREACH(const CTxOut& txout, tx.vout)
132             if (IsMine(txout))
133                 return true;
134         return false;
135     }
136     bool IsFromMe(const CTransaction& tx) const
137     {
138         return (GetDebit(tx) > 0);
139     }
140     int64_t GetDebit(const CTransaction& tx) const
141     {
142         int64_t nDebit = 0;
143         BOOST_FOREACH(const CTxIn& txin, tx.vin)
144         {
145             nDebit += GetDebit(txin);
146             if (!MoneyRange(nDebit))
147                 throw std::runtime_error("CWallet::GetDebit() : value out of range");
148         }
149         return nDebit;
150     }
151     int64_t GetCredit(const CTransaction& tx) const
152     {
153         int64_t nCredit = 0;
154         BOOST_FOREACH(const CTxOut& txout, tx.vout)
155         {
156             nCredit += GetCredit(txout);
157             if (!MoneyRange(nCredit))
158                 throw std::runtime_error("CWallet::GetCredit() : value out of range");
159         }
160         return nCredit;
161     }
162     int64_t GetChange(const CTransaction& tx) const
163     {
164         int64_t nChange = 0;
165         BOOST_FOREACH(const CTxOut& txout, tx.vout)
166         {
167             nChange += GetChange(txout);
168             if (!MoneyRange(nChange))
169                 throw std::runtime_error("CWallet::GetChange() : value out of range");
170         }
171         return nChange;
172     }
173     void SetBestChain(const CBlockLocator& loc)
174     {
175         CWalletDB walletdb(strWalletFile);
176         walletdb.WriteBestBlock(loc);
177     }
178
179     int LoadWallet(bool& fFirstRunRet);
180 //    bool BackupWallet(const std::string& strDest);
181
182     bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
183
184     bool DelAddressBookName(const CBitcoinAddress& address);
185
186     void UpdatedTransaction(const uint256 &hashTx)
187     {
188         CRITICAL_BLOCK(cs_wallet)
189             vWalletUpdated.push_back(hashTx);
190     }
191
192     void PrintWallet(const CBlock& block);
193
194     void Inventory(const uint256 &hash)
195     {
196         CRITICAL_BLOCK(cs_wallet)
197         {
198             std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
199             if (mi != mapRequestCount.end())
200                 (*mi).second++;
201         }
202     }
203
204     int GetKeyPoolSize()
205     {
206         return setKeyPool.size();
207     }
208
209     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
210
211     bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);
212 };
213
214
215 class CReserveKey
216 {
217 protected:
218     CWallet* pwallet;
219     int64_t nIndex;
220     std::vector<unsigned char> vchPubKey;
221 public:
222     CReserveKey(CWallet* pwalletIn)
223     {
224         nIndex = -1;
225         pwallet = pwalletIn;
226     }
227
228     ~CReserveKey()
229     {
230         if (!fShutdown)
231             ReturnKey();
232     }
233
234     void ReturnKey();
235     std::vector<unsigned char> GetReservedKey();
236     void KeepKey();
237 };
238
239
240 //
241 // A transaction with a bunch of additional info that only the owner cares
242 // about.  It includes any unrecorded transactions needed to link it back
243 // to the block chain.
244 //
245 class CWalletTx : public CMerkleTx
246 {
247 private:
248     const CWallet* pwallet;
249
250 public:
251     std::vector<CMerkleTx> vtxPrev;
252     std::map<std::string, std::string> mapValue;
253     std::vector<std::pair<std::string, std::string> > vOrderForm;
254     unsigned int fTimeReceivedIsTxTime;
255     unsigned int nTimeReceived;  // time received by this node
256     char fFromMe;
257     std::string strFromAccount;
258     std::vector<char> vfSpent; // which outputs are already spent
259
260     // memory only
261     mutable char fDebitCached;
262     mutable char fCreditCached;
263     mutable char fAvailableCreditCached;
264     mutable char fChangeCached;
265     mutable int64_t nDebitCached;
266     mutable int64_t nCreditCached;
267     mutable int64_t nAvailableCreditCached;
268     mutable int64_t nChangeCached;
269
270     // memory only UI hints
271     mutable unsigned int nTimeDisplayed;
272     mutable int nLinesDisplayed;
273     mutable char fConfirmedDisplayed;
274
275     CWalletTx()
276     {
277         Init(NULL);
278     }
279
280     CWalletTx(const CWallet* pwalletIn)
281     {
282         Init(pwalletIn);
283     }
284
285     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
286     {
287         Init(pwalletIn);
288     }
289
290     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
291     {
292         Init(pwalletIn);
293     }
294
295     void Init(const CWallet* pwalletIn)
296     {
297         pwallet = pwalletIn;
298         vtxPrev.clear();
299         mapValue.clear();
300         vOrderForm.clear();
301         fTimeReceivedIsTxTime = false;
302         nTimeReceived = 0;
303         fFromMe = false;
304         strFromAccount.clear();
305         vfSpent.clear();
306         fDebitCached = false;
307         fCreditCached = false;
308         fAvailableCreditCached = false;
309         fChangeCached = false;
310         nDebitCached = 0;
311         nCreditCached = 0;
312         nAvailableCreditCached = 0;
313         nChangeCached = 0;
314         nTimeDisplayed = 0;
315         nLinesDisplayed = 0;
316         fConfirmedDisplayed = false;
317     }
318
319     IMPLEMENT_SERIALIZE
320     (
321         CWalletTx* pthis = const_cast<CWalletTx*>(this);
322         if (fRead)
323             pthis->Init(NULL);
324         char fSpent = false;
325
326         if (!fRead)
327         {
328             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
329
330             std::string str;
331             BOOST_FOREACH(char f, vfSpent)
332             {
333                 str += (f ? '1' : '0');
334                 if (f)
335                     fSpent = true;
336             }
337             pthis->mapValue["spent"] = str;
338         }
339
340         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
341         READWRITE(vtxPrev);
342         READWRITE(mapValue);
343         READWRITE(vOrderForm);
344         READWRITE(fTimeReceivedIsTxTime);
345         READWRITE(nTimeReceived);
346         READWRITE(fFromMe);
347         READWRITE(fSpent);
348
349         if (fRead)
350         {
351             pthis->strFromAccount = pthis->mapValue["fromaccount"];
352
353             if (mapValue.count("spent"))
354                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
355                     pthis->vfSpent.push_back(c != '0');
356             else
357                 pthis->vfSpent.assign(vout.size(), fSpent);
358         }
359
360         pthis->mapValue.erase("fromaccount");
361         pthis->mapValue.erase("version");
362         pthis->mapValue.erase("spent");
363     )
364
365     // marks certain txout's as spent
366     // returns true if any update took place
367     bool UpdateSpent(const std::vector<char>& vfNewSpent)
368     {
369         bool fReturn = false;
370         for (int i=0; i < vfNewSpent.size(); i++)
371         {
372             if (i == vfSpent.size())
373                 break;
374
375             if (vfNewSpent[i] && !vfSpent[i])
376             {
377                 vfSpent[i] = true;
378                 fReturn = true;
379                 fAvailableCreditCached = false;
380             }
381         }
382         return fReturn;
383     }
384
385     // make sure balances are recalculated
386     void MarkDirty()
387     {
388         fCreditCached = false;
389         fAvailableCreditCached = false;
390         fDebitCached = false;
391         fChangeCached = false;
392     }
393
394     void BindWallet(CWallet *pwalletIn)
395     {
396         pwallet = pwalletIn;
397         MarkDirty();
398     }
399
400     void MarkSpent(unsigned int nOut)
401     {
402         if (nOut >= vout.size())
403             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
404         vfSpent.resize(vout.size());
405         if (!vfSpent[nOut])
406         {
407             vfSpent[nOut] = true;
408             fAvailableCreditCached = false;
409         }
410     }
411
412     bool IsSpent(unsigned int nOut) const
413     {
414         if (nOut >= vout.size())
415             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
416         if (nOut >= vfSpent.size())
417             return false;
418         return (!!vfSpent[nOut]);
419     }
420
421     int64_t GetDebit() const
422     {
423         if (vin.empty())
424             return 0;
425         if (fDebitCached)
426             return nDebitCached;
427         nDebitCached = pwallet->GetDebit(*this);
428         fDebitCached = true;
429         return nDebitCached;
430     }
431
432     int64_t GetCredit(bool fUseCache=true) const
433     {
434         // Must wait until coinbase is safely deep enough in the chain before valuing it
435         if (IsCoinBase() && GetBlocksToMaturity() > 0)
436             return 0;
437
438         // GetBalance can assume transactions in mapWallet won't change
439         if (fUseCache && fCreditCached)
440             return nCreditCached;
441         nCreditCached = pwallet->GetCredit(*this);
442         fCreditCached = true;
443         return nCreditCached;
444     }
445
446     int64_t GetAvailableCredit(bool fUseCache=true) const
447     {
448         // Must wait until coinbase is safely deep enough in the chain before valuing it
449         if (IsCoinBase() && GetBlocksToMaturity() > 0)
450             return 0;
451
452         if (fUseCache && fAvailableCreditCached)
453             return nAvailableCreditCached;
454
455         int64_t nCredit = 0;
456         for (int i = 0; i < vout.size(); i++)
457         {
458             if (!IsSpent(i))
459             {
460                 const CTxOut &txout = vout[i];
461                 nCredit += pwallet->GetCredit(txout);
462                 if (!MoneyRange(nCredit))
463                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
464             }
465         }
466
467         nAvailableCreditCached = nCredit;
468         fAvailableCreditCached = true;
469         return nCredit;
470     }
471
472
473     int64_t GetChange() const
474     {
475         if (fChangeCached)
476             return nChangeCached;
477         nChangeCached = pwallet->GetChange(*this);
478         fChangeCached = true;
479         return nChangeCached;
480     }
481
482     void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
483                     std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount) const;
484
485     void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived, 
486                            int64_t& nSent, int64_t& nFee) const;
487
488     bool IsFromMe() const
489     {
490         return (GetDebit() > 0);
491     }
492
493     bool IsConfirmed() const
494     {
495         // Quick answer in most cases
496         if (!IsFinal())
497             return false;
498         if (GetDepthInMainChain() >= 1)
499             return true;
500         if (!IsFromMe()) // using wtx's cached debit
501             return false;
502
503         // If no confirmations but it's from us, we can still
504         // consider it confirmed if all dependencies are confirmed
505         std::map<uint256, const CMerkleTx*> mapPrev;
506         std::vector<const CMerkleTx*> vWorkQueue;
507         vWorkQueue.reserve(vtxPrev.size()+1);
508         vWorkQueue.push_back(this);
509         for (int i = 0; i < vWorkQueue.size(); i++)
510         {
511             const CMerkleTx* ptx = vWorkQueue[i];
512
513             if (!ptx->IsFinal())
514                 return false;
515             if (ptx->GetDepthInMainChain() >= 1)
516                 continue;
517             if (!pwallet->IsFromMe(*ptx))
518                 return false;
519
520             if (mapPrev.empty())
521                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
522                     mapPrev[tx.GetHash()] = &tx;
523
524             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
525             {
526                 if (!mapPrev.count(txin.prevout.hash))
527                     return false;
528                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
529             }
530         }
531         return true;
532     }
533
534     bool WriteToDisk();
535
536     int64_t GetTxTime() const;
537     int GetRequestCount() const;
538
539     void AddSupportingTransactions(CTxDB& txdb);
540
541     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
542     bool AcceptWalletTransaction();
543
544     void RelayWalletTransaction(CTxDB& txdb);
545     void RelayWalletTransaction();
546 };
547
548
549 //
550 // Private key that includes an expiration date in case it never gets used.
551 //
552 class CWalletKey
553 {
554 public:
555     CPrivKey vchPrivKey;
556     int64_t nTimeCreated;
557     int64_t nTimeExpires;
558     std::string strComment;
559     //// todo: add something to note what created it (user, getnewaddress, change)
560     ////   maybe should have a map<string, string> property map
561
562     CWalletKey(int64_t nExpires=0)
563     {
564         nTimeCreated = (nExpires ? GetTime() : 0);
565         nTimeExpires = nExpires;
566     }
567
568     IMPLEMENT_SERIALIZE
569     (
570         if (!(nType & SER_GETHASH))
571             READWRITE(nVersion);
572         READWRITE(vchPrivKey);
573         READWRITE(nTimeCreated);
574         READWRITE(nTimeExpires);
575         READWRITE(strComment);
576     )
577 };
578
579
580
581
582
583
584 //
585 // Account information.
586 // Stored in wallet with key "acc"+string account name
587 //
588 class CAccount
589 {
590 public:
591     std::vector<unsigned char> vchPubKey;
592
593     CAccount()
594     {
595         SetNull();
596     }
597
598     void SetNull()
599     {
600         vchPubKey.clear();
601     }
602
603     IMPLEMENT_SERIALIZE
604     (
605         if (!(nType & SER_GETHASH))
606             READWRITE(nVersion);
607         READWRITE(vchPubKey);
608     )
609 };
610
611
612
613 //
614 // Internal transfers.
615 // Database key is acentry<account><counter>
616 //
617 class CAccountingEntry
618 {
619 public:
620     std::string strAccount;
621     int64_t nCreditDebit;
622     int64_t nTime;
623     std::string strOtherAccount;
624     std::string strComment;
625
626     CAccountingEntry()
627     {
628         SetNull();
629     }
630
631     void SetNull()
632     {
633         nCreditDebit = 0;
634         nTime = 0;
635         strAccount.clear();
636         strOtherAccount.clear();
637         strComment.clear();
638     }
639
640     IMPLEMENT_SERIALIZE
641     (
642         if (!(nType & SER_GETHASH))
643             READWRITE(nVersion);
644         // Note: strAccount is serialized as part of the key, not here.
645         READWRITE(nCreditDebit);
646         READWRITE(nTime);
647         READWRITE(strOtherAccount);
648         READWRITE(strComment);
649     )
650 };
651
652 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
653
654 #endif