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