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