PPCoin: stakeonly mode for RPC command 'walletpassphrase'
[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
218
219 class CReserveKey
220 {
221 protected:
222     CWallet* pwallet;
223     int64 nIndex;
224     std::vector<unsigned char> vchPubKey;
225 public:
226     CReserveKey(CWallet* pwalletIn)
227     {
228         nIndex = -1;
229         pwallet = pwalletIn;
230     }
231
232     ~CReserveKey()
233     {
234         if (!fShutdown)
235             ReturnKey();
236     }
237
238     void ReturnKey();
239     std::vector<unsigned char> GetReservedKey();
240     void KeepKey();
241 };
242
243
244 //
245 // A transaction with a bunch of additional info that only the owner cares
246 // about.  It includes any unrecorded transactions needed to link it back
247 // to the block chain.
248 //
249 class CWalletTx : public CMerkleTx
250 {
251 public:
252     const CWallet* pwallet;
253
254     std::vector<CMerkleTx> vtxPrev;
255     std::map<std::string, std::string> mapValue;
256     std::vector<std::pair<std::string, std::string> > vOrderForm;
257     unsigned int fTimeReceivedIsTxTime;
258     unsigned int nTimeReceived;  // time received by this node
259     char fFromMe;
260     std::string strFromAccount;
261     std::vector<char> vfSpent; // which outputs are already spent
262
263     // memory only
264     mutable char fDebitCached;
265     mutable char fCreditCached;
266     mutable char fAvailableCreditCached;
267     mutable char fChangeCached;
268     mutable int64 nDebitCached;
269     mutable int64 nCreditCached;
270     mutable int64 nAvailableCreditCached;
271     mutable int64 nChangeCached;
272
273     // memory only UI hints
274     mutable unsigned int nTimeDisplayed;
275     mutable int nLinesDisplayed;
276     mutable char fConfirmedDisplayed;
277
278     CWalletTx()
279     {
280         Init(NULL);
281     }
282
283     CWalletTx(const CWallet* pwalletIn)
284     {
285         Init(pwalletIn);
286     }
287
288     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
289     {
290         Init(pwalletIn);
291     }
292
293     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
294     {
295         Init(pwalletIn);
296     }
297
298     void Init(const CWallet* pwalletIn)
299     {
300         pwallet = pwalletIn;
301         vtxPrev.clear();
302         mapValue.clear();
303         vOrderForm.clear();
304         fTimeReceivedIsTxTime = false;
305         nTimeReceived = 0;
306         fFromMe = false;
307         strFromAccount.clear();
308         vfSpent.clear();
309         fDebitCached = false;
310         fCreditCached = false;
311         fAvailableCreditCached = false;
312         fChangeCached = false;
313         nDebitCached = 0;
314         nCreditCached = 0;
315         nAvailableCreditCached = 0;
316         nChangeCached = 0;
317         nTimeDisplayed = 0;
318         nLinesDisplayed = 0;
319         fConfirmedDisplayed = false;
320     }
321
322     IMPLEMENT_SERIALIZE
323     (
324         CWalletTx* pthis = const_cast<CWalletTx*>(this);
325         if (fRead)
326             pthis->Init(NULL);
327         char fSpent = false;
328
329         if (!fRead)
330         {
331             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
332
333             std::string str;
334             BOOST_FOREACH(char f, vfSpent)
335             {
336                 str += (f ? '1' : '0');
337                 if (f)
338                     fSpent = true;
339             }
340             pthis->mapValue["spent"] = str;
341         }
342
343         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
344         READWRITE(vtxPrev);
345         READWRITE(mapValue);
346         READWRITE(vOrderForm);
347         READWRITE(fTimeReceivedIsTxTime);
348         READWRITE(nTimeReceived);
349         READWRITE(fFromMe);
350         READWRITE(fSpent);
351
352         if (fRead)
353         {
354             pthis->strFromAccount = pthis->mapValue["fromaccount"];
355
356             if (mapValue.count("spent"))
357                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
358                     pthis->vfSpent.push_back(c != '0');
359             else
360                 pthis->vfSpent.assign(vout.size(), fSpent);
361         }
362
363         pthis->mapValue.erase("fromaccount");
364         pthis->mapValue.erase("version");
365         pthis->mapValue.erase("spent");
366     )
367
368     // marks certain txout's as spent
369     // returns true if any update took place
370     bool UpdateSpent(const std::vector<char>& vfNewSpent)
371     {
372         bool fReturn = false;
373         for (int i=0; i < vfNewSpent.size(); i++)
374         {
375             if (i == vfSpent.size())
376                 break;
377
378             if (vfNewSpent[i] && !vfSpent[i])
379             {
380                 vfSpent[i] = true;
381                 fReturn = true;
382                 fAvailableCreditCached = false;
383             }
384         }
385         return fReturn;
386     }
387
388     // make sure balances are recalculated
389     void MarkDirty()
390     {
391         fCreditCached = false;
392         fAvailableCreditCached = false;
393         fDebitCached = false;
394         fChangeCached = false;
395     }
396
397     void MarkSpent(unsigned int nOut)
398     {
399         if (nOut >= vout.size())
400             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
401         vfSpent.resize(vout.size());
402         if (!vfSpent[nOut])
403         {
404             vfSpent[nOut] = true;
405             fAvailableCreditCached = false;
406         }
407     }
408
409     bool IsSpent(unsigned int nOut) const
410     {
411         if (nOut >= vout.size())
412             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
413         if (nOut >= vfSpent.size())
414             return false;
415         return (!!vfSpent[nOut]);
416     }
417
418     int64 GetDebit() const
419     {
420         if (vin.empty())
421             return 0;
422         if (fDebitCached)
423             return nDebitCached;
424         nDebitCached = pwallet->GetDebit(*this);
425         fDebitCached = true;
426         return nDebitCached;
427     }
428
429     int64 GetCredit(bool fUseCache=true) const
430     {
431         // Must wait until coinbase is safely deep enough in the chain before valuing it
432         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
433             return 0;
434
435         // GetBalance can assume transactions in mapWallet won't change
436         if (fUseCache && fCreditCached)
437             return nCreditCached;
438         nCreditCached = pwallet->GetCredit(*this);
439         fCreditCached = true;
440         return nCreditCached;
441     }
442
443     int64 GetAvailableCredit(bool fUseCache=true) const
444     {
445         // Must wait until coinbase is safely deep enough in the chain before valuing it
446         if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
447             return 0;
448
449         if (fUseCache && fAvailableCreditCached)
450             return nAvailableCreditCached;
451
452         int64 nCredit = 0;
453         for (int i = 0; i < vout.size(); i++)
454         {
455             if (!IsSpent(i))
456             {
457                 const CTxOut &txout = vout[i];
458                 nCredit += pwallet->GetCredit(txout);
459                 if (!MoneyRange(nCredit))
460                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
461             }
462         }
463
464         nAvailableCreditCached = nCredit;
465         fAvailableCreditCached = true;
466         return nCredit;
467     }
468
469
470     int64 GetChange() const
471     {
472         if (fChangeCached)
473             return nChangeCached;
474         nChangeCached = pwallet->GetChange(*this);
475         fChangeCached = true;
476         return nChangeCached;
477     }
478
479     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64> >& listReceived,
480                     std::list<std::pair<CBitcoinAddress, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
481
482     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived, 
483                            int64& nSent, int64& nFee) const;
484
485     bool IsFromMe() const
486     {
487         return (GetDebit() > 0);
488     }
489
490     bool IsConfirmed() const
491     {
492         // Quick answer in most cases
493         if (!IsFinal())
494             return false;
495         if (GetDepthInMainChain() >= 1)
496             return true;
497         if (!IsFromMe()) // using wtx's cached debit
498             return false;
499
500         // If no confirmations but it's from us, we can still
501         // consider it confirmed if all dependencies are confirmed
502         std::map<uint256, const CMerkleTx*> mapPrev;
503         std::vector<const CMerkleTx*> vWorkQueue;
504         vWorkQueue.reserve(vtxPrev.size()+1);
505         vWorkQueue.push_back(this);
506         for (int i = 0; i < vWorkQueue.size(); i++)
507         {
508             const CMerkleTx* ptx = vWorkQueue[i];
509
510             if (!ptx->IsFinal())
511                 return false;
512             if (ptx->GetDepthInMainChain() >= 1)
513                 continue;
514             if (!pwallet->IsFromMe(*ptx))
515                 return false;
516
517             if (mapPrev.empty())
518                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
519                     mapPrev[tx.GetHash()] = &tx;
520
521             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
522             {
523                 if (!mapPrev.count(txin.prevout.hash))
524                     return false;
525                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
526             }
527         }
528         return true;
529     }
530
531     bool WriteToDisk();
532
533     int64 GetTxTime() const;
534     int GetRequestCount() const;
535
536     void AddSupportingTransactions(CTxDB& txdb);
537
538     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
539     bool AcceptWalletTransaction();
540
541     void RelayWalletTransaction(CTxDB& txdb);
542     void RelayWalletTransaction();
543 };
544
545
546 //
547 // Private key that includes an expiration date in case it never gets used.
548 //
549 class CWalletKey
550 {
551 public:
552     CPrivKey vchPrivKey;
553     int64 nTimeCreated;
554     int64 nTimeExpires;
555     std::string strComment;
556     //// todo: add something to note what created it (user, getnewaddress, change)
557     ////   maybe should have a map<string, string> property map
558
559     CWalletKey(int64 nExpires=0)
560     {
561         nTimeCreated = (nExpires ? GetTime() : 0);
562         nTimeExpires = nExpires;
563     }
564
565     IMPLEMENT_SERIALIZE
566     (
567         if (!(nType & SER_GETHASH))
568             READWRITE(nVersion);
569         READWRITE(vchPrivKey);
570         READWRITE(nTimeCreated);
571         READWRITE(nTimeExpires);
572         READWRITE(strComment);
573     )
574 };
575
576
577
578
579
580
581 //
582 // Account information.
583 // Stored in wallet with key "acc"+string account name
584 //
585 class CAccount
586 {
587 public:
588     std::vector<unsigned char> vchPubKey;
589
590     CAccount()
591     {
592         SetNull();
593     }
594
595     void SetNull()
596     {
597         vchPubKey.clear();
598     }
599
600     IMPLEMENT_SERIALIZE
601     (
602         if (!(nType & SER_GETHASH))
603             READWRITE(nVersion);
604         READWRITE(vchPubKey);
605     )
606 };
607
608
609
610 //
611 // Internal transfers.
612 // Database key is acentry<account><counter>
613 //
614 class CAccountingEntry
615 {
616 public:
617     std::string strAccount;
618     int64 nCreditDebit;
619     int64 nTime;
620     std::string strOtherAccount;
621     std::string strComment;
622
623     CAccountingEntry()
624     {
625         SetNull();
626     }
627
628     void SetNull()
629     {
630         nCreditDebit = 0;
631         nTime = 0;
632         strAccount.clear();
633         strOtherAccount.clear();
634         strComment.clear();
635     }
636
637     IMPLEMENT_SERIALIZE
638     (
639         if (!(nType & SER_GETHASH))
640             READWRITE(nVersion);
641         // Note: strAccount is serialized as part of the key, not here.
642         READWRITE(nCreditDebit);
643         READWRITE(nTime);
644         READWRITE(strOtherAccount);
645         READWRITE(strComment);
646     )
647 };
648
649 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
650
651 #endif