Update CMakeLists.txt - play with openssl
[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 "main.h"
9 #include "interface.h"
10 #include "walletdb.h"
11
12 extern unsigned int nStakeMaxAge;
13 extern bool fWalletUnlockMintOnly;
14 extern bool fConfChange;
15 class CAccountingEntry;
16 class CWalletTx;
17 class CReserveKey;
18 class COutput;
19 class CCoinControl;
20
21 // Set of selected transactions
22 typedef std::set<std::pair<const CWalletTx*,unsigned int> > CoinsSet;
23
24 /** (client) version numbers for particular wallet features */
25 enum WalletFeature
26 {
27     FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
28
29     FEATURE_WALLETCRYPT = 40000, // wallet encryption
30     FEATURE_COMPRPUBKEY = 60000, // compressed public keys
31     FEATURE_MALLKEY = 60017,
32     FEATURE_LATEST = 60017
33 };
34
35 /** A key pool entry */
36 class CKeyPool
37 {
38 public:
39     int64_t nTime;
40     CPubKey vchPubKey;
41
42     CKeyPool();
43
44     CKeyPool(const CPubKey& vchPubKeyIn);
45
46     IMPLEMENT_SERIALIZE
47     (
48         if (!(nType & SER_GETHASH))
49             READWRITE(nVersion);
50         READWRITE(nTime);
51         READWRITE(vchPubKey);
52     )
53 };
54
55 /** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
56  * and provides the ability to create new transactions.
57  */
58 class CWallet : public CCryptoKeyStore
59 {
60 private:
61     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;
62
63     CWalletDB *pwalletdbEncryption, *pwalletdbDecryption;
64
65     // the current wallet version: clients below this version are not able to load the wallet
66     int nWalletVersion;
67
68     // the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
69     int nWalletMaxVersion;
70
71     int64_t nNextResend;
72     int64_t nLastResend;
73
74     // stake mining statistics
75     uint64_t nKernelsTried;
76     uint64_t nCoinDaysTried;
77
78 public:
79     mutable CCriticalSection cs_wallet;
80
81     bool fFileBacked;
82     std::string strWalletFile;
83
84     std::set<int64_t> setKeyPool;
85     /*
86     std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
87     std::map<CMalleableKeyView, CKeyMetadata> mapMalleableKeyMetadata;
88     */
89
90     std::map<CBitcoinAddress, CKeyMetadata> mapKeyMetadata;
91
92     typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
93     MasterKeyMap mapMasterKeys;
94     unsigned int nMasterKeyMaxID;
95
96     CWallet();
97     CWallet(std::string strWalletFileIn);
98     void SetNull();
99
100     std::map<uint256, CWalletTx> mapWallet;
101     std::vector<uint256> vMintingWalletUpdated;
102     int64_t nOrderPosNext;
103     std::map<uint256, int> mapRequestCount;
104
105     std::map<CBitcoinAddress, std::string> mapAddressBook;
106
107     CPubKey vchDefaultKey;
108     int64_t nTimeFirstKey;
109
110     const CWalletTx* GetWalletTx(const uint256& hash) const;
111
112     // check whether we are allowed to upgrade (or already support) to the named feature
113     bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
114
115     void AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const;
116     void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const;
117     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;
118
119     // Simple select (without randomization)
120     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;
121
122     // keystore implementation
123     // Generate a new key
124     CPubKey GenerateNewKey();
125     CMalleableKeyView GenerateNewMalleableKey();
126     // Adds a key to the store, and saves it to disk.
127     bool AddKey(const CKey& key);
128     bool AddKey(const CMalleableKey& mKey);
129     // Adds a key to the store, without saving it to disk (used by LoadWallet)
130     bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
131     // Load metadata (used by LoadWallet)
132     bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
133     bool LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata);
134
135     // Load malleable key without saving it to disk (used by LoadWallet)
136     bool LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH);
137     bool LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH);
138
139     bool LoadMinVersion(int nVersion);
140
141     // Adds an encrypted key to the store, and saves it to disk.
142     bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
143     bool AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH);
144     // Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
145     bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
146     bool AddCScript(const CScript& redeemScript);
147     bool LoadCScript(const CScript& redeemScript);
148
149     // Adds a watch-only address to the store, and saves it to disk.
150     bool AddWatchOnly(const CScript &dest);
151     bool RemoveWatchOnly(const CScript &dest);
152     // Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
153     bool LoadWatchOnly(const CScript &dest);
154
155     bool Unlock(const SecureString& strWalletPassphrase);
156     bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
157     bool EncryptWallet(const SecureString& strWalletPassphrase);
158     bool DecryptWallet(const SecureString& strWalletPassphrase);
159
160     void GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const;
161
162
163     /** Increment the next transaction order id
164         @return next transaction order id
165      */
166     int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
167
168     typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
169     typedef std::multimap<int64_t, TxPair > TxItems;
170
171     /** Get the wallet's activity log
172         @return multimap of ordered transactions and accounting entries
173         @warning Returned pointers are *only* valid within the scope of passed acentries
174      */
175     TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
176
177     void MarkDirty();
178     bool AddToWallet(const CWalletTx& wtxIn);
179     bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
180     bool EraseFromWallet(uint256 hash);
181     void ClearOrphans();
182     void WalletUpdateSpent(const CTransaction& prevout, bool fBlock = false);
183     int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
184     int ScanForWalletTransaction(const uint256& hashTx);
185     void ReacceptWalletTransactions();
186     void ResendWalletTransactions(int64_t nBestBlockTime);
187     std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
188     int64_t GetBalance() const;
189     int64_t GetWatchOnlyBalance() const;
190     int64_t GetUnconfirmedBalance() const;
191     int64_t GetUnconfirmedWatchOnlyBalance() const;
192     int64_t GetImmatureBalance() const;
193     int64_t GetImmatureWatchOnlyBalance() const;
194     int64_t GetStake() const;
195     int64_t GetNewMint() const;
196     int64_t GetWatchOnlyStake() const;
197     int64_t GetWatchOnlyNewMint() const;
198     bool CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
199     bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL);
200     bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
201
202     void GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight);
203     bool CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nTime, uint32_t nBits, CTransaction &txNew, CKey& key);
204     bool MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nMaxValue, std::list<uint256>& listMerged);
205
206     std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false);
207
208     bool NewKeyPool(unsigned int nSize = 0);
209     bool TopUpKeyPool(unsigned int nSize = 0);
210     int64_t AddReserveKey(const CKeyPool& keypool);
211     void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
212     void KeepKey(int64_t nIndex);
213     void ReturnKey(int64_t nIndex);
214     bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
215     int64_t GetOldestKeyPoolTime();
216     void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
217
218     std::set< std::set<CBitcoinAddress> > GetAddressGroupings();
219     std::map<CBitcoinAddress, int64_t> GetAddressBalances();
220
221     isminetype IsMine(const CTxIn& txin) const;
222     int64_t GetDebit(const CTxIn& txin, const isminefilter& filter) const;
223     isminetype IsMine(const CTxOut& txout) const;
224     int64_t GetCredit(const CTxOut& txout, const isminefilter& filter) const;
225     bool IsChange(const CTxOut& txout) const;
226     int64_t GetChange(const CTxOut& txout) const;
227     bool IsMine(const CTransaction& tx) const;
228     bool IsFromMe(const CTransaction& tx) const;
229     int64_t GetDebit(const CTransaction& tx, const isminefilter& filter) const;
230     int64_t GetCredit(const CTransaction& tx, const isminefilter& filter) const;
231     int64_t GetChange(const CTransaction& tx) const;
232     void SetBestChain(const CBlockLocator& loc);
233
234     DBErrors LoadWallet(bool& fFirstRunRet);
235     DBErrors ZapWalletTx();
236
237     bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
238     bool SetAddressBookName(const CBitcoinAddress& address, const std::string& strName);
239     bool DelAddressBookName(const CBitcoinAddress& address);
240     void UpdatedTransaction(const uint256 &hashTx);
241     void PrintWallet(const CBlock& block);
242
243     void Inventory(const uint256 &hash);
244
245     unsigned int GetKeyPoolSize();
246
247     bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
248     bool SetDefaultKey(const CPubKey &vchPubKey);
249
250     // signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
251     bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
252
253     // change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
254     bool SetMaxVersion(int nVersion);
255
256     // get the current wallet format (the oldest client version guaranteed to understand this wallet)
257     int GetVersion() { return nWalletVersion; }
258
259     void FixSpentCoins(int& nMismatchSpent, int64_t& nBalanceInQuestion, bool fCheckOnly = false);
260     void DisableTransaction(const CTransaction &tx);
261
262     /** Address book entry changed.
263      * @note called with lock cs_wallet held.
264      */
265     boost::signals2::signal<void (CWallet *wallet, const CBitcoinAddress &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
266
267     /** Wallet transaction added, removed or updated.
268      * @note called with lock cs_wallet held.
269      */
270     boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
271
272     /** Watch-only address added */
273     boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
274 };
275
276 /** A key allocated from the key pool. */
277 class CReserveKey
278 {
279 protected:
280     CWallet* pwallet;
281     int64_t nIndex;
282     CPubKey vchPubKey;
283 public:
284     CReserveKey(CWallet* pwalletIn);
285
286     ~CReserveKey();
287
288     void ReturnKey();
289     CPubKey GetReservedKey();
290     void KeepKey();
291 };
292
293
294 typedef std::map<std::string, std::string> mapValue_t;
295
296
297 /** A transaction with a bunch of additional info that only the owner cares about.
298  * It includes any unrecorded transactions needed to link it back to the block chain.
299  */
300 class CWalletTx : public CMerkleTx
301 {
302 private:
303     const CWallet* pwallet;
304
305 public:
306     std::vector<CMerkleTx> vtxPrev;
307     mapValue_t mapValue;
308     std::vector<std::pair<std::string, std::string> > vOrderForm;
309     unsigned int fTimeReceivedIsTxTime;
310     unsigned int nTimeReceived;  // time received by this node
311     unsigned int nTimeSmart;
312     char fFromMe;
313     std::string strFromAccount;
314     std::vector<char> vfSpent; // which outputs are already spent
315     int64_t nOrderPos;  // position in ordered transaction list
316
317     // memory only
318     mutable bool fDebitCached;
319     mutable bool fWatchDebitCached;
320     mutable bool fCreditCached;
321     mutable bool fWatchCreditCached;
322     mutable bool fAvailableCreditCached;
323     mutable bool fImmatureCreditCached;
324     mutable bool fImmatureWatchCreditCached;
325     mutable bool fAvailableWatchCreditCached;
326     mutable bool fChangeCached;
327     mutable int64_t nDebitCached;
328     mutable int64_t nWatchDebitCached;
329     mutable int64_t nCreditCached;
330     mutable int64_t nWatchCreditCached;
331     mutable int64_t nAvailableCreditCached;
332     mutable int64_t nImmatureCreditCached;
333     mutable int64_t nImmatureWatchCreditCached;
334     mutable int64_t nAvailableWatchCreditCached;
335     mutable int64_t nChangeCached;
336
337     CWalletTx();
338     CWalletTx(const CWallet* pwalletIn);
339     CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn);
340     CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn);
341
342     void Init(const CWallet* pwalletIn);
343
344     IMPLEMENT_SERIALIZE
345     (
346         CWalletTx* pthis = const_cast<CWalletTx*>(this);
347         if (fRead)
348             pthis->Init(NULL);
349         char fSpent = false;
350
351         if (!fRead)
352         {
353             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
354
355             std::string str;
356             for (char f : vfSpent)
357             {
358                 str += (f ? '1' : '0');
359                 if (f)
360                     fSpent = true;
361             }
362             pthis->mapValue["spent"] = str;
363
364             if (pthis->nOrderPos != -1)
365                 pthis->mapValue["n"] = i64tostr(pthis->nOrderPos);
366
367             if (nTimeSmart)
368                 pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
369         }
370
371         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
372         READWRITE(vtxPrev);
373         READWRITE(mapValue);
374         READWRITE(vOrderForm);
375         READWRITE(fTimeReceivedIsTxTime);
376         READWRITE(nTimeReceived);
377         READWRITE(fFromMe);
378         READWRITE(fSpent);
379
380         if (fRead)
381         {
382             pthis->strFromAccount = pthis->mapValue["fromaccount"];
383
384             if (mapValue.count("spent"))
385                 for (char c : pthis->mapValue["spent"])
386                     pthis->vfSpent.push_back(c != '0');
387             else
388                 pthis->vfSpent.assign(vout.size(), fSpent);
389
390             const auto it_op = pthis->mapValue.find("n");
391             pthis->nOrderPos = (it_op != pthis->mapValue.end()) ? atoi64(it_op->second.c_str()) : -1;
392
393             pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
394         }
395
396         pthis->mapValue.erase("fromaccount");
397         pthis->mapValue.erase("version");
398         pthis->mapValue.erase("spent");
399         pthis->mapValue.erase("n");
400         pthis->mapValue.erase("timesmart");
401     )
402
403     // marks certain txout's as spent
404     // returns true if any update took place
405     bool UpdateSpent(const std::vector<char>& vfNewSpent);
406
407     // make sure balances are recalculated
408     void MarkDirty();
409     void BindWallet(CWallet *pwalletIn);
410     void MarkSpent(unsigned int nOut);
411     void MarkUnspent(unsigned int nOut);
412     bool IsSpent(unsigned int nOut) const;
413
414     int64_t GetDebit(const isminefilter& filter) const;
415     int64_t GetCredit(const isminefilter& filter) const;
416     int64_t GetImmatureCredit(bool fUseCache=true) const;
417     int64_t GetImmatureWatchOnlyCredit(bool fUseCache=true) const;
418     int64_t GetAvailableCredit(bool fUseCache=true) const;
419     int64_t GetAvailableWatchCredit(bool fUseCache=true) const;
420     int64_t GetChange() const;
421
422     void GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, std::list<std::pair<CBitcoinAddress, int64_t> >& listReceived,
423                     std::list<std::pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, std::string& strSentAccount, const isminefilter& filter) const;
424
425     void GetAccountAmounts(const std::string& strAccount, int64_t& nGenerated, int64_t& nReceived,
426                            int64_t& nSent, int64_t& nFee, const isminefilter& filter) const;
427
428     bool IsFromMe(const isminefilter& filter) const;
429
430     bool InMempool() const;
431     bool IsTrusted() const;
432
433     bool WriteToDisk();
434
435     int64_t GetTxTime() const;
436     int GetRequestCount() const;
437
438     void AddSupportingTransactions(CTxDB& txdb);
439
440     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
441     bool AcceptWalletTransaction();
442
443     bool RelayWalletTransaction(CTxDB& txdb);
444     bool RelayWalletTransaction();
445 };
446
447
448
449
450 class COutput
451 {
452 public:
453     const CWalletTx *tx;
454     int i;
455     int nDepth;
456     bool fSpendable;
457
458     COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn);
459
460     std::string ToString() const;
461 };
462
463
464
465
466 /** Private key that includes an expiration date in case it never gets used. */
467 class CWalletKey
468 {
469 public:
470     CPrivKey vchPrivKey;
471     int64_t nTimeCreated;
472     int64_t nTimeExpires;
473     std::string strComment;
474     //// todo: add something to note what created it (user, getnewaddress, change)
475     ////   maybe should have a map<string, string> property map
476
477     CWalletKey(int64_t nExpires=0);
478
479     IMPLEMENT_SERIALIZE
480     (
481         if (!(nType & SER_GETHASH))
482             READWRITE(nVersion);
483         READWRITE(vchPrivKey);
484         READWRITE(nTimeCreated);
485         READWRITE(nTimeExpires);
486         READWRITE(strComment);
487     )
488 };
489
490
491
492
493
494
495 /** Account information.
496  * Stored in wallet with key "acc"+string account name.
497  */
498 class CAccount
499 {
500 public:
501     CPubKey vchPubKey;
502
503     CAccount();
504
505     void SetNull();
506
507     IMPLEMENT_SERIALIZE
508     (
509         if (!(nType & SER_GETHASH))
510             READWRITE(nVersion);
511         READWRITE(vchPubKey);
512     )
513 };
514
515
516
517 /** Internal transfers.
518  * Database key is acentry<account><counter>.
519  */
520 class CAccountingEntry
521 {
522 public:
523     std::string strAccount;
524     int64_t nCreditDebit;
525     int64_t nTime;
526     std::string strOtherAccount;
527     std::string strComment;
528     mapValue_t mapValue;
529     int64_t nOrderPos;  // position in ordered transaction list
530     uint64_t nEntryNo;
531
532     CAccountingEntry();
533
534     void SetNull();
535
536     IMPLEMENT_SERIALIZE
537     (
538         CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
539         if (!(nType & SER_GETHASH))
540             READWRITE(nVersion);
541         // Note: strAccount is serialized as part of the key, not here.
542         READWRITE(nCreditDebit);
543         READWRITE(nTime);
544         READWRITE(strOtherAccount);
545
546         if (!fRead)
547         {
548             if (nOrderPos != -1)
549                 me.mapValue["n"] = i64tostr(nOrderPos);
550
551             if (!(mapValue.empty() && _ssExtra.empty()))
552             {
553                 CDataStream ss(nType, nVersion);
554                 ss.insert(ss.begin(), '\0');
555                 ss << mapValue;
556                 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
557                 me.strComment.append(ss.str());
558             }
559         }
560
561         READWRITE(strComment);
562
563         size_t nSepPos = strComment.find("\0", 0, 1);
564         if (fRead)
565         {
566             me.mapValue.clear();
567             if (std::string::npos != nSepPos)
568             {
569                 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
570                 ss >> me.mapValue;
571                 me._ssExtra = std::vector<char>(ss.begin(), ss.end());
572             }
573             const auto it_op = me.mapValue.find("n");
574             me.nOrderPos = (it_op != me.mapValue.end()) ? atoi64(it_op->second.c_str()) : -1;
575         }
576         if (std::string::npos != nSepPos)
577             me.strComment.erase(nSepPos);
578
579         me.mapValue.erase("n");
580     )
581
582 private:
583     std::vector<char> _ssExtra;
584 };
585
586 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
587
588 #endif