Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2014 The Bitcoin Core developers
3 : // Distributed under the MIT software license, see the accompanying
4 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 :
6 : #ifndef BITCOIN_WALLET_WALLET_H
7 : #define BITCOIN_WALLET_WALLET_H
8 :
9 : #include "amount.h"
10 : #include "streams.h"
11 : #include "tinyformat.h"
12 : #include "ui_interface.h"
13 : #include "utilstrencodings.h"
14 : #include "validationinterface.h"
15 : #include "wallet/crypter.h"
16 : #include "wallet/wallet_ismine.h"
17 : #include "wallet/walletdb.h"
18 :
19 : #include <algorithm>
20 : #include <map>
21 : #include <set>
22 : #include <stdexcept>
23 : #include <stdint.h>
24 : #include <string>
25 : #include <utility>
26 : #include <vector>
27 :
28 : #include <boost/shared_ptr.hpp>
29 :
30 : /**
31 : * Settings
32 : */
33 : extern CFeeRate payTxFee;
34 : extern CAmount maxTxFee;
35 : extern unsigned int nTxConfirmTarget;
36 : extern bool bSpendZeroConfChange;
37 : extern bool fSendFreeTransactions;
38 : extern bool fPayAtLeastCustomFee;
39 :
40 : //! -paytxfee default
41 : static const CAmount DEFAULT_TRANSACTION_FEE = 0;
42 : //! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
43 : static const CAmount nHighTransactionFeeWarning = 0.01 * COIN;
44 : //! -maxtxfee default
45 : static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.1 * COIN;
46 : //! -txconfirmtarget default
47 : static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 2;
48 : //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
49 : static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning;
50 : //! Largest (in bytes) free transaction we're willing to create
51 : static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
52 :
53 : class CAccountingEntry;
54 : class CBlockIndex;
55 : class CCoinControl;
56 : class COutput;
57 : class CReserveKey;
58 : class CScript;
59 : class CTxMemPool;
60 : class CWalletTx;
61 :
62 : /** (client) version numbers for particular wallet features */
63 : enum WalletFeature
64 : {
65 : FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
66 :
67 : FEATURE_WALLETCRYPT = 40000, // wallet encryption
68 : FEATURE_COMPRPUBKEY = 60000, // compressed public keys
69 :
70 : FEATURE_LATEST = 60000
71 : };
72 :
73 :
74 : /** A key pool entry */
75 : class CKeyPool
76 : {
77 : public:
78 : int64_t nTime;
79 : CPubKey vchPubKey;
80 :
81 : CKeyPool();
82 : CKeyPool(const CPubKey& vchPubKeyIn);
83 :
84 2346 : ADD_SERIALIZE_METHODS;
85 :
86 : template <typename Stream, typename Operation>
87 2346 : inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
88 2346 : if (!(nType & SER_GETHASH))
89 2346 : READWRITE(nVersion);
90 2346 : READWRITE(nTime);
91 2346 : READWRITE(vchPubKey);
92 2346 : }
93 : };
94 :
95 : /** Address book data */
96 5040 : class CAddressBookData
97 : {
98 : public:
99 : std::string name;
100 : std::string purpose;
101 :
102 380 : CAddressBookData()
103 1140 : {
104 380 : purpose = "unknown";
105 380 : }
106 :
107 : typedef std::map<std::string, std::string> StringMap;
108 : StringMap destdata;
109 : };
110 :
111 1072 : struct CRecipient
112 : {
113 : CScript scriptPubKey;
114 : CAmount nAmount;
115 : bool fSubtractFeeFromAmount;
116 : };
117 :
118 : typedef std::map<std::string, std::string> mapValue_t;
119 :
120 :
121 2768 : static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
122 : {
123 11072 : if (!mapValue.count("n"))
124 : {
125 3 : nOrderPos = -1; // TODO: calculate elsewhere
126 2771 : return;
127 : }
128 11060 : nOrderPos = atoi64(mapValue["n"].c_str());
129 : }
130 :
131 :
132 1899 : static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
133 : {
134 1899 : if (nOrderPos == -1)
135 1899 : return;
136 7584 : mapValue["n"] = i64tostr(nOrderPos);
137 : }
138 :
139 6896 : struct COutputEntry
140 : {
141 : CTxDestination destination;
142 : CAmount amount;
143 : int vout;
144 : };
145 :
146 : /** A transaction with a merkle branch linking it to the block chain. */
147 121641 : class CMerkleTx : public CTransaction
148 : {
149 : private:
150 : int GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const;
151 :
152 : public:
153 : uint256 hashBlock;
154 : int nIndex;
155 :
156 10263 : CMerkleTx()
157 10263 : {
158 10263 : Init();
159 10263 : }
160 :
161 19991 : CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
162 : {
163 19991 : Init();
164 19991 : }
165 :
166 30254 : void Init()
167 : {
168 30254 : hashBlock = uint256();
169 30254 : nIndex = -1;
170 30254 : }
171 :
172 4633 : ADD_SERIALIZE_METHODS;
173 :
174 : template <typename Stream, typename Operation>
175 4633 : inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
176 : std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
177 4633 : READWRITE(*(CTransaction*)this);
178 4633 : nVersion = this->nVersion;
179 4633 : READWRITE(hashBlock);
180 4633 : READWRITE(vMerkleBranch);
181 4633 : READWRITE(nIndex);
182 4633 : }
183 :
184 : int SetMerkleBranch(const CBlock& block);
185 :
186 :
187 : /**
188 : * Return depth of transaction in blockchain:
189 : * -1 : not in blockchain, and not in memory pool (conflicted transaction)
190 : * 0 : in memory pool, waiting to be included in a block
191 : * >=1 : this many blocks deep in the main chain
192 : */
193 : int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
194 85900 : int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
195 1 : bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
196 : int GetBlocksToMaturity() const;
197 : bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true);
198 : };
199 :
200 : /**
201 : * A transaction with a bunch of additional info that only the owner cares about.
202 : * It includes any unrecorded transactions needed to link it back to the block chain.
203 : */
204 249691 : class CWalletTx : public CMerkleTx
205 : {
206 : private:
207 : const CWallet* pwallet;
208 :
209 : public:
210 : mapValue_t mapValue;
211 : std::vector<std::pair<std::string, std::string> > vOrderForm;
212 : unsigned int fTimeReceivedIsTxTime;
213 : unsigned int nTimeReceived; //! time received by this node
214 : unsigned int nTimeSmart;
215 : char fFromMe;
216 : std::string strFromAccount;
217 : int64_t nOrderPos; //! position in ordered transaction list
218 :
219 : // memory only
220 : mutable bool fDebitCached;
221 : mutable bool fCreditCached;
222 : mutable bool fImmatureCreditCached;
223 : mutable bool fAvailableCreditCached;
224 : mutable bool fWatchDebitCached;
225 : mutable bool fWatchCreditCached;
226 : mutable bool fImmatureWatchCreditCached;
227 : mutable bool fAvailableWatchCreditCached;
228 : mutable bool fChangeCached;
229 : mutable CAmount nDebitCached;
230 : mutable CAmount nCreditCached;
231 : mutable CAmount nImmatureCreditCached;
232 : mutable CAmount nAvailableCreditCached;
233 : mutable CAmount nWatchDebitCached;
234 : mutable CAmount nWatchCreditCached;
235 : mutable CAmount nImmatureWatchCreditCached;
236 : mutable CAmount nAvailableWatchCreditCached;
237 : mutable CAmount nChangeCached;
238 :
239 5630 : CWalletTx()
240 16890 : {
241 5630 : Init(NULL);
242 5630 : }
243 :
244 : CWalletTx(const CWallet* pwalletIn)
245 : {
246 : Init(pwalletIn);
247 : }
248 :
249 : CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
250 : {
251 : Init(pwalletIn);
252 : }
253 :
254 59973 : CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
255 : {
256 19991 : Init(pwalletIn);
257 19991 : }
258 :
259 28365 : void Init(const CWallet* pwalletIn)
260 : {
261 28365 : pwallet = pwalletIn;
262 28365 : mapValue.clear();
263 28365 : vOrderForm.clear();
264 28365 : fTimeReceivedIsTxTime = false;
265 28365 : nTimeReceived = 0;
266 28365 : nTimeSmart = 0;
267 28365 : fFromMe = false;
268 28365 : strFromAccount.clear();
269 28365 : fDebitCached = false;
270 28365 : fCreditCached = false;
271 28365 : fImmatureCreditCached = false;
272 28365 : fAvailableCreditCached = false;
273 28365 : fWatchDebitCached = false;
274 28365 : fWatchCreditCached = false;
275 28365 : fImmatureWatchCreditCached = false;
276 28365 : fAvailableWatchCreditCached = false;
277 28365 : fChangeCached = false;
278 28365 : nDebitCached = 0;
279 28365 : nCreditCached = 0;
280 28365 : nImmatureCreditCached = 0;
281 28365 : nAvailableCreditCached = 0;
282 28365 : nWatchDebitCached = 0;
283 28365 : nWatchCreditCached = 0;
284 28365 : nAvailableWatchCreditCached = 0;
285 28365 : nImmatureWatchCreditCached = 0;
286 28365 : nChangeCached = 0;
287 28365 : nOrderPos = -1;
288 28365 : }
289 :
290 4633 : ADD_SERIALIZE_METHODS;
291 :
292 : template <typename Stream, typename Operation>
293 4633 : inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
294 4633 : if (ser_action.ForRead())
295 2744 : Init(NULL);
296 4633 : char fSpent = false;
297 :
298 4633 : if (!ser_action.ForRead())
299 : {
300 5667 : mapValue["fromaccount"] = strFromAccount;
301 :
302 1889 : WriteOrderPos(nOrderPos, mapValue);
303 :
304 1889 : if (nTimeSmart)
305 7556 : mapValue["timesmart"] = strprintf("%u", nTimeSmart);
306 : }
307 :
308 4633 : READWRITE(*(CMerkleTx*)this);
309 : std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
310 4633 : READWRITE(vUnused);
311 4633 : READWRITE(mapValue);
312 4633 : READWRITE(vOrderForm);
313 4633 : READWRITE(fTimeReceivedIsTxTime);
314 4633 : READWRITE(nTimeReceived);
315 4633 : READWRITE(fFromMe);
316 4633 : READWRITE(fSpent);
317 :
318 4633 : if (ser_action.ForRead())
319 : {
320 8232 : strFromAccount = mapValue["fromaccount"];
321 :
322 2744 : ReadOrderPos(nOrderPos, mapValue);
323 :
324 16464 : nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
325 : }
326 :
327 13899 : mapValue.erase("fromaccount");
328 13899 : mapValue.erase("version");
329 13899 : mapValue.erase("spent");
330 13899 : mapValue.erase("n");
331 13899 : mapValue.erase("timesmart");
332 4633 : }
333 :
334 : //! make sure balances are recalculated
335 : void MarkDirty()
336 : {
337 12360 : fCreditCached = false;
338 12360 : fAvailableCreditCached = false;
339 12360 : fWatchDebitCached = false;
340 12360 : fWatchCreditCached = false;
341 12360 : fAvailableWatchCreditCached = false;
342 12360 : fImmatureWatchCreditCached = false;
343 12360 : fDebitCached = false;
344 12360 : fChangeCached = false;
345 : }
346 :
347 : void BindWallet(CWallet *pwalletIn)
348 : {
349 7212 : pwallet = pwalletIn;
350 : MarkDirty();
351 : }
352 :
353 : //! filter decides which addresses will count towards the debit
354 : CAmount GetDebit(const isminefilter& filter) const;
355 : CAmount GetCredit(const isminefilter& filter) const;
356 : CAmount GetImmatureCredit(bool fUseCache=true) const;
357 : CAmount GetAvailableCredit(bool fUseCache=true) const;
358 : CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
359 : CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
360 : CAmount GetChange() const;
361 :
362 : void GetAmounts(std::list<COutputEntry>& listReceived,
363 : std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
364 :
365 : void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
366 : CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
367 :
368 : bool IsFromMe(const isminefilter& filter) const
369 : {
370 148592 : return (GetDebit(filter) > 0);
371 : }
372 :
373 : // True if only scriptSigs are different
374 : bool IsEquivalentTo(const CWalletTx& tx) const;
375 :
376 : bool IsTrusted() const;
377 :
378 : bool WriteToDisk(CWalletDB *pwalletdb);
379 :
380 : int64_t GetTxTime() const;
381 : int GetRequestCount() const;
382 :
383 : bool RelayWalletTransaction();
384 :
385 : std::set<uint256> GetConflicts() const;
386 : };
387 :
388 :
389 :
390 :
391 : class COutput
392 : {
393 : public:
394 : const CWalletTx *tx;
395 : int i;
396 : int nDepth;
397 : bool fSpendable;
398 :
399 0 : COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
400 : {
401 20847 : tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
402 0 : }
403 :
404 : std::string ToString() const;
405 : };
406 :
407 :
408 :
409 :
410 : /** Private key that includes an expiration date in case it never gets used. */
411 0 : class CWalletKey
412 : {
413 : public:
414 : CPrivKey vchPrivKey;
415 : int64_t nTimeCreated;
416 : int64_t nTimeExpires;
417 : std::string strComment;
418 : //! todo: add something to note what created it (user, getnewaddress, change)
419 : //! maybe should have a map<string, string> property map
420 :
421 : CWalletKey(int64_t nExpires=0);
422 :
423 0 : ADD_SERIALIZE_METHODS;
424 :
425 : template <typename Stream, typename Operation>
426 0 : inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
427 0 : if (!(nType & SER_GETHASH))
428 0 : READWRITE(nVersion);
429 0 : READWRITE(vchPrivKey);
430 0 : READWRITE(nTimeCreated);
431 0 : READWRITE(nTimeExpires);
432 0 : READWRITE(LIMITED_STRING(strComment, 65536));
433 0 : }
434 : };
435 :
436 :
437 :
438 : /**
439 : * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
440 : * and provides the ability to create new transactions.
441 : */
442 : class CWallet : public CCryptoKeyStore, public CValidationInterface
443 : {
444 : private:
445 : bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL) const;
446 :
447 : CWalletDB *pwalletdbEncryption;
448 :
449 : //! the current wallet version: clients below this version are not able to load the wallet
450 : int nWalletVersion;
451 :
452 : //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
453 : int nWalletMaxVersion;
454 :
455 : int64_t nNextResend;
456 : int64_t nLastResend;
457 : bool fBroadcastTransactions;
458 :
459 : /**
460 : * Used to keep track of spent outpoints, and
461 : * detect and report conflicts (double-spends or
462 : * mutated transactions where the mutant gets mined).
463 : */
464 : typedef std::multimap<COutPoint, uint256> TxSpends;
465 : TxSpends mapTxSpends;
466 : void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
467 : void AddToSpends(const uint256& wtxid);
468 :
469 : void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
470 :
471 : public:
472 : /*
473 : * Main wallet lock.
474 : * This lock protects all the fields added by CWallet
475 : * except for:
476 : * fFileBacked (immutable after instantiation)
477 : * strWalletFile (immutable after instantiation)
478 : */
479 : mutable CCriticalSection cs_wallet;
480 :
481 : bool fFileBacked;
482 : std::string strWalletFile;
483 :
484 : std::set<int64_t> setKeyPool;
485 : std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
486 :
487 : typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
488 : MasterKeyMap mapMasterKeys;
489 : unsigned int nMasterKeyMaxID;
490 :
491 1 : CWallet()
492 17 : {
493 : SetNull();
494 1 : }
495 :
496 120 : CWallet(const std::string& strWalletFileIn)
497 2040 : {
498 : SetNull();
499 :
500 120 : strWalletFile = strWalletFileIn;
501 120 : fFileBacked = true;
502 120 : }
503 :
504 241 : ~CWallet()
505 1936 : {
506 121 : delete pwalletdbEncryption;
507 121 : pwalletdbEncryption = NULL;
508 241 : }
509 :
510 : void SetNull()
511 : {
512 121 : nWalletVersion = FEATURE_BASE;
513 121 : nWalletMaxVersion = FEATURE_BASE;
514 121 : fFileBacked = false;
515 121 : nMasterKeyMaxID = 0;
516 121 : pwalletdbEncryption = NULL;
517 121 : nOrderPosNext = 0;
518 121 : nNextResend = 0;
519 121 : nLastResend = 0;
520 121 : nTimeFirstKey = 0;
521 121 : fBroadcastTransactions = false;
522 : }
523 :
524 : std::map<uint256, CWalletTx> mapWallet;
525 :
526 : int64_t nOrderPosNext;
527 : std::map<uint256, int> mapRequestCount;
528 :
529 : std::map<CTxDestination, CAddressBookData> mapAddressBook;
530 :
531 : CPubKey vchDefaultKey;
532 :
533 : std::set<COutPoint> setLockedCoins;
534 :
535 : int64_t nTimeFirstKey;
536 :
537 : const CWalletTx* GetWalletTx(const uint256& hash) const;
538 :
539 : //! check whether we are allowed to upgrade (or already support) to the named feature
540 1056 : bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
541 :
542 : void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false) const;
543 : bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const;
544 :
545 : bool IsSpent(const uint256& hash, unsigned int n) const;
546 :
547 : bool IsLockedCoin(uint256 hash, unsigned int n) const;
548 : void LockCoin(COutPoint& output);
549 : void UnlockCoin(COutPoint& output);
550 : void UnlockAllCoins();
551 : void ListLockedCoins(std::vector<COutPoint>& vOutpts);
552 :
553 : /**
554 : * keystore implementation
555 : * Generate a new key
556 : */
557 : CPubKey GenerateNewKey();
558 : //! Adds a key to the store, and saves it to disk.
559 : bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
560 : //! Adds a key to the store, without saving it to disk (used by LoadWallet)
561 2598 : bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
562 : //! Load metadata (used by LoadWallet)
563 : bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
564 :
565 116 : bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
566 :
567 : //! Adds an encrypted key to the store, and saves it to disk.
568 : bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
569 : //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
570 : bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
571 : bool AddCScript(const CScript& redeemScript);
572 : bool LoadCScript(const CScript& redeemScript);
573 :
574 : //! Adds a destination data tuple to the store, and saves it to disk
575 : bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
576 : //! Erases a destination data tuple in the store and on disk
577 : bool EraseDestData(const CTxDestination &dest, const std::string &key);
578 : //! Adds a destination data tuple to the store, without saving it to disk
579 : bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
580 : //! Look up a destination data tuple in the store, return true if found false otherwise
581 : bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
582 :
583 : //! Adds a watch-only address to the store, and saves it to disk.
584 : bool AddWatchOnly(const CScript &dest);
585 : bool RemoveWatchOnly(const CScript &dest);
586 : //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
587 : bool LoadWatchOnly(const CScript &dest);
588 :
589 : bool Unlock(const SecureString& strWalletPassphrase);
590 : bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
591 : bool EncryptWallet(const SecureString& strWalletPassphrase);
592 :
593 : void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
594 :
595 : /**
596 : * Increment the next transaction order id
597 : * @return next transaction order id
598 : */
599 : int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
600 :
601 : typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
602 : typedef std::multimap<int64_t, TxPair > TxItems;
603 :
604 : /**
605 : * Get the wallet's activity log
606 : * @return multimap of ordered transactions and accounting entries
607 : * @warning Returned pointers are *only* valid within the scope of passed acentries
608 : */
609 : TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
610 :
611 : void MarkDirty();
612 : bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
613 : void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
614 : bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
615 : int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
616 : void ReacceptWalletTransactions();
617 : void ResendWalletTransactions(int64_t nBestBlockTime);
618 : std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime);
619 : CAmount GetBalance() const;
620 : CAmount GetUnconfirmedBalance() const;
621 : CAmount GetImmatureBalance() const;
622 : CAmount GetWatchOnlyBalance() const;
623 : CAmount GetUnconfirmedWatchOnlyBalance() const;
624 : CAmount GetImmatureWatchOnlyBalance() const;
625 : bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, bool includeWatching);
626 : bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet,
627 : std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true);
628 : bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
629 :
630 : static CFeeRate minTxFee;
631 : static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
632 :
633 : bool NewKeyPool();
634 : bool TopUpKeyPool(unsigned int kpSize = 0);
635 : void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
636 : void KeepKey(int64_t nIndex);
637 : void ReturnKey(int64_t nIndex);
638 : bool GetKeyFromPool(CPubKey &key);
639 : int64_t GetOldestKeyPoolTime();
640 : void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
641 :
642 : std::set< std::set<CTxDestination> > GetAddressGroupings();
643 : std::map<CTxDestination, CAmount> GetAddressBalances();
644 :
645 : std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
646 :
647 : isminetype IsMine(const CTxIn& txin) const;
648 : CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
649 : isminetype IsMine(const CTxOut& txout) const;
650 : CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
651 : bool IsChange(const CTxOut& txout) const;
652 : CAmount GetChange(const CTxOut& txout) const;
653 : bool IsMine(const CTransaction& tx) const;
654 : /** should probably be renamed to IsRelevantToMe */
655 : bool IsFromMe(const CTransaction& tx) const;
656 : CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
657 : CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
658 : CAmount GetChange(const CTransaction& tx) const;
659 : void SetBestChain(const CBlockLocator& loc);
660 :
661 : DBErrors LoadWallet(bool& fFirstRunRet);
662 : DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
663 :
664 : bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
665 :
666 : bool DelAddressBook(const CTxDestination& address);
667 :
668 : void UpdatedTransaction(const uint256 &hashTx);
669 :
670 12484 : void Inventory(const uint256 &hash)
671 : {
672 : {
673 12484 : LOCK(cs_wallet);
674 24968 : std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
675 24968 : if (mi != mapRequestCount.end())
676 329 : (*mi).second++;
677 : }
678 12484 : }
679 :
680 : void GetScriptForMining(boost::shared_ptr<CReserveScript> &script);
681 0 : void ResetRequestCount(const uint256 &hash)
682 : {
683 0 : LOCK(cs_wallet);
684 0 : mapRequestCount[hash] = 0;
685 0 : };
686 :
687 : unsigned int GetKeyPoolSize()
688 : {
689 2 : AssertLockHeld(cs_wallet); // setKeyPool
690 4 : return setKeyPool.size();
691 : }
692 :
693 : bool SetDefaultKey(const CPubKey &vchPubKey);
694 :
695 : //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
696 : bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
697 :
698 : //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
699 : bool SetMaxVersion(int nVersion);
700 :
701 : //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
702 78 : int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
703 :
704 : //! Get wallet transactions that conflict with given transaction (spend same outputs)
705 : std::set<uint256> GetConflicts(const uint256& txid) const;
706 :
707 : //! Flush wallet (bitdb flush)
708 : void Flush(bool shutdown=false);
709 :
710 : //! Verify the wallet database and perform salvage if required
711 : static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
712 :
713 : /**
714 : * Address book entry changed.
715 : * @note called with lock cs_wallet held.
716 : */
717 : boost::signals2::signal<void (CWallet *wallet, const CTxDestination
718 : &address, const std::string &label, bool isMine,
719 : const std::string &purpose,
720 : ChangeType status)> NotifyAddressBookChanged;
721 :
722 : /**
723 : * Wallet transaction added, removed or updated.
724 : * @note called with lock cs_wallet held.
725 : */
726 : boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
727 : ChangeType status)> NotifyTransactionChanged;
728 :
729 : /** Show progress e.g. for rescan */
730 : boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
731 :
732 : /** Watch-only address added */
733 : boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
734 :
735 : /** Inquire whether this wallet broadcasts transactions. */
736 0 : bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
737 : /** Set whether this wallet broadcasts transactions. */
738 94 : void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
739 : };
740 :
741 : /** A key allocated from the key pool. */
742 : class CReserveKey : public CReserveScript
743 : {
744 : protected:
745 : CWallet* pwallet;
746 : int64_t nIndex;
747 : CPubKey vchPubKey;
748 : public:
749 0 : CReserveKey(CWallet* pwalletIn)
750 842 : {
751 421 : nIndex = -1;
752 421 : pwallet = pwalletIn;
753 0 : }
754 :
755 695 : ~CReserveKey()
756 842 : {
757 147 : ReturnKey();
758 695 : }
759 :
760 : void ReturnKey();
761 : bool GetReservedKey(CPubKey &pubkey);
762 : void KeepKey();
763 1236 : void KeepScript() { KeepKey(); }
764 : };
765 :
766 :
767 : /**
768 : * Account information.
769 : * Stored in wallet with key "acc"+string account name.
770 : */
771 : class CAccount
772 : {
773 : public:
774 : CPubKey vchPubKey;
775 :
776 0 : CAccount()
777 6 : {
778 : SetNull();
779 0 : }
780 :
781 : void SetNull()
782 : {
783 5 : vchPubKey = CPubKey();
784 : }
785 :
786 6 : ADD_SERIALIZE_METHODS;
787 :
788 : template <typename Stream, typename Operation>
789 6 : inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
790 6 : if (!(nType & SER_GETHASH))
791 6 : READWRITE(nVersion);
792 6 : READWRITE(vchPubKey);
793 6 : }
794 : };
795 :
796 :
797 :
798 : /**
799 : * Internal transfers.
800 : * Database key is acentry<account><counter>.
801 : */
802 666 : class CAccountingEntry
803 : {
804 : public:
805 : std::string strAccount;
806 : CAmount nCreditDebit;
807 : int64_t nTime;
808 : std::string strOtherAccount;
809 : std::string strComment;
810 : mapValue_t mapValue;
811 : int64_t nOrderPos; //! position in ordered transaction list
812 : uint64_t nEntryNo;
813 :
814 37 : CAccountingEntry()
815 185 : {
816 37 : SetNull();
817 37 : }
818 :
819 37 : void SetNull()
820 : {
821 37 : nCreditDebit = 0;
822 37 : nTime = 0;
823 37 : strAccount.clear();
824 37 : strOtherAccount.clear();
825 37 : strComment.clear();
826 37 : nOrderPos = -1;
827 37 : nEntryNo = 0;
828 37 : }
829 :
830 34 : ADD_SERIALIZE_METHODS;
831 :
832 : template <typename Stream, typename Operation>
833 34 : inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
834 34 : if (!(nType & SER_GETHASH))
835 34 : READWRITE(nVersion);
836 : //! Note: strAccount is serialized as part of the key, not here.
837 34 : READWRITE(nCreditDebit);
838 34 : READWRITE(nTime);
839 102 : READWRITE(LIMITED_STRING(strOtherAccount, 65536));
840 :
841 34 : if (!ser_action.ForRead())
842 : {
843 10 : WriteOrderPos(nOrderPos, mapValue);
844 :
845 23 : if (!(mapValue.empty() && _ssExtra.empty()))
846 : {
847 7 : CDataStream ss(nType, nVersion);
848 14 : ss.insert(ss.begin(), '\0');
849 7 : ss << mapValue;
850 35 : ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
851 14 : strComment.append(ss.str());
852 : }
853 : }
854 :
855 102 : READWRITE(LIMITED_STRING(strComment, 65536));
856 :
857 34 : size_t nSepPos = strComment.find("\0", 0, 1);
858 34 : if (ser_action.ForRead())
859 : {
860 24 : mapValue.clear();
861 24 : if (std::string::npos != nSepPos)
862 : {
863 105 : CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
864 21 : ss >> mapValue;
865 84 : _ssExtra = std::vector<char>(ss.begin(), ss.end());
866 : }
867 24 : ReadOrderPos(nOrderPos, mapValue);
868 : }
869 34 : if (std::string::npos != nSepPos)
870 28 : strComment.erase(nSepPos);
871 :
872 102 : mapValue.erase("n");
873 34 : }
874 :
875 : private:
876 : std::vector<char> _ssExtra;
877 : };
878 :
879 : #endif // BITCOIN_WALLET_WALLET_H
|