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