Get rid of nType and nVersion
[bitcoinplatinum.git] / src / wallet / wallet.h
bloba527c6d84ef1bdcae39ad9700b8e86e5f9b19897
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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.
6 #ifndef BITCOIN_WALLET_WALLET_H
7 #define BITCOIN_WALLET_WALLET_H
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 "script/ismine.h"
16 #include "wallet/crypter.h"
17 #include "wallet/walletdb.h"
18 #include "wallet/rpcwallet.h"
20 #include <algorithm>
21 #include <map>
22 #include <set>
23 #include <stdexcept>
24 #include <stdint.h>
25 #include <string>
26 #include <utility>
27 #include <vector>
29 #include <boost/shared_ptr.hpp>
30 #include <boost/thread.hpp>
32 extern CWallet* pwalletMain;
34 /**
35 * Settings
37 extern CFeeRate payTxFee;
38 extern unsigned int nTxConfirmTarget;
39 extern bool bSpendZeroConfChange;
40 extern bool fSendFreeTransactions;
41 extern bool fWalletRbf;
43 static const unsigned int DEFAULT_KEYPOOL_SIZE = 100;
44 //! -paytxfee default
45 static const CAmount DEFAULT_TRANSACTION_FEE = 0;
46 //! -fallbackfee default
47 static const CAmount DEFAULT_FALLBACK_FEE = 20000;
48 //! -mintxfee default
49 static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
50 //! minimum change amount
51 static const CAmount MIN_CHANGE = CENT;
52 //! Default for -spendzeroconfchange
53 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
54 //! Default for -sendfreetransactions
55 static const bool DEFAULT_SEND_FREE_TRANSACTIONS = false;
56 //! -txconfirmtarget default
57 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
58 //! -walletrbf default
59 static const bool DEFAULT_WALLET_RBF = false;
60 //! Largest (in bytes) free transaction we're willing to create
61 static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
62 static const bool DEFAULT_WALLETBROADCAST = true;
63 static const bool DEFAULT_DISABLE_WALLET = false;
64 //! if set, all keys will be derived by using BIP32
65 static const bool DEFAULT_USE_HD_WALLET = true;
67 extern const char * DEFAULT_WALLET_DAT;
69 class CBlockIndex;
70 class CCoinControl;
71 class COutput;
72 class CReserveKey;
73 class CScript;
74 class CTxMemPool;
75 class CWalletTx;
77 /** (client) version numbers for particular wallet features */
78 enum WalletFeature
80 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
82 FEATURE_WALLETCRYPT = 40000, // wallet encryption
83 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
85 FEATURE_HD = 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
86 FEATURE_LATEST = FEATURE_COMPRPUBKEY // HD is optional, use FEATURE_COMPRPUBKEY as latest version
90 /** A key pool entry */
91 class CKeyPool
93 public:
94 int64_t nTime;
95 CPubKey vchPubKey;
97 CKeyPool();
98 CKeyPool(const CPubKey& vchPubKeyIn);
100 ADD_SERIALIZE_METHODS;
102 template <typename Stream, typename Operation>
103 inline void SerializationOp(Stream& s, Operation ser_action) {
104 int nVersion = s.GetVersion();
105 if (!(s.GetType() & SER_GETHASH))
106 READWRITE(nVersion);
107 READWRITE(nTime);
108 READWRITE(vchPubKey);
112 /** Address book data */
113 class CAddressBookData
115 public:
116 std::string name;
117 std::string purpose;
119 CAddressBookData()
121 purpose = "unknown";
124 typedef std::map<std::string, std::string> StringMap;
125 StringMap destdata;
128 struct CRecipient
130 CScript scriptPubKey;
131 CAmount nAmount;
132 bool fSubtractFeeFromAmount;
135 typedef std::map<std::string, std::string> mapValue_t;
138 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
140 if (!mapValue.count("n"))
142 nOrderPos = -1; // TODO: calculate elsewhere
143 return;
145 nOrderPos = atoi64(mapValue["n"].c_str());
149 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
151 if (nOrderPos == -1)
152 return;
153 mapValue["n"] = i64tostr(nOrderPos);
156 struct COutputEntry
158 CTxDestination destination;
159 CAmount amount;
160 int vout;
163 /** A transaction with a merkle branch linking it to the block chain. */
164 class CMerkleTx : public CTransaction
166 private:
167 /** Constant used in hashBlock to indicate tx has been abandoned */
168 static const uint256 ABANDON_HASH;
170 public:
171 uint256 hashBlock;
173 /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
174 * block in the chain we know this or any in-wallet dependency conflicts
175 * with. Older clients interpret nIndex == -1 as unconfirmed for backward
176 * compatibility.
178 int nIndex;
180 CMerkleTx()
182 Init();
185 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
187 Init();
190 void Init()
192 hashBlock = uint256();
193 nIndex = -1;
196 ADD_SERIALIZE_METHODS;
198 template <typename Stream, typename Operation>
199 inline void SerializationOp(Stream& s, Operation ser_action) {
200 std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
201 READWRITE(*(CTransaction*)this);
202 READWRITE(hashBlock);
203 READWRITE(vMerkleBranch);
204 READWRITE(nIndex);
207 int SetMerkleBranch(const CBlockIndex* pIndex, int posInBlock);
210 * Return depth of transaction in blockchain:
211 * <0 : conflicts with a transaction this deep in the blockchain
212 * 0 : in memory pool, waiting to be included in a block
213 * >=1 : this many blocks deep in the main chain
215 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
216 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
217 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; }
218 int GetBlocksToMaturity() const;
219 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
220 bool AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state);
221 bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
222 bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
223 void setAbandoned() { hashBlock = ABANDON_HASH; }
226 /**
227 * A transaction with a bunch of additional info that only the owner cares about.
228 * It includes any unrecorded transactions needed to link it back to the block chain.
230 class CWalletTx : public CMerkleTx
232 private:
233 const CWallet* pwallet;
235 public:
236 mapValue_t mapValue;
237 std::vector<std::pair<std::string, std::string> > vOrderForm;
238 unsigned int fTimeReceivedIsTxTime;
239 unsigned int nTimeReceived; //!< time received by this node
240 unsigned int nTimeSmart;
241 char fFromMe;
242 std::string strFromAccount;
243 int64_t nOrderPos; //!< position in ordered transaction list
245 // memory only
246 mutable bool fDebitCached;
247 mutable bool fCreditCached;
248 mutable bool fImmatureCreditCached;
249 mutable bool fAvailableCreditCached;
250 mutable bool fWatchDebitCached;
251 mutable bool fWatchCreditCached;
252 mutable bool fImmatureWatchCreditCached;
253 mutable bool fAvailableWatchCreditCached;
254 mutable bool fChangeCached;
255 mutable CAmount nDebitCached;
256 mutable CAmount nCreditCached;
257 mutable CAmount nImmatureCreditCached;
258 mutable CAmount nAvailableCreditCached;
259 mutable CAmount nWatchDebitCached;
260 mutable CAmount nWatchCreditCached;
261 mutable CAmount nImmatureWatchCreditCached;
262 mutable CAmount nAvailableWatchCreditCached;
263 mutable CAmount nChangeCached;
265 CWalletTx()
267 Init(NULL);
270 CWalletTx(const CWallet* pwalletIn)
272 Init(pwalletIn);
275 CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
277 Init(pwalletIn);
280 CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
282 Init(pwalletIn);
285 void Init(const CWallet* pwalletIn)
287 pwallet = pwalletIn;
288 mapValue.clear();
289 vOrderForm.clear();
290 fTimeReceivedIsTxTime = false;
291 nTimeReceived = 0;
292 nTimeSmart = 0;
293 fFromMe = false;
294 strFromAccount.clear();
295 fDebitCached = false;
296 fCreditCached = false;
297 fImmatureCreditCached = false;
298 fAvailableCreditCached = false;
299 fWatchDebitCached = false;
300 fWatchCreditCached = false;
301 fImmatureWatchCreditCached = false;
302 fAvailableWatchCreditCached = false;
303 fChangeCached = false;
304 nDebitCached = 0;
305 nCreditCached = 0;
306 nImmatureCreditCached = 0;
307 nAvailableCreditCached = 0;
308 nWatchDebitCached = 0;
309 nWatchCreditCached = 0;
310 nAvailableWatchCreditCached = 0;
311 nImmatureWatchCreditCached = 0;
312 nChangeCached = 0;
313 nOrderPos = -1;
316 ADD_SERIALIZE_METHODS;
318 template <typename Stream, typename Operation>
319 inline void SerializationOp(Stream& s, Operation ser_action) {
320 if (ser_action.ForRead())
321 Init(NULL);
322 char fSpent = false;
324 if (!ser_action.ForRead())
326 mapValue["fromaccount"] = strFromAccount;
328 WriteOrderPos(nOrderPos, mapValue);
330 if (nTimeSmart)
331 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
334 READWRITE(*(CMerkleTx*)this);
335 std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
336 READWRITE(vUnused);
337 READWRITE(mapValue);
338 READWRITE(vOrderForm);
339 READWRITE(fTimeReceivedIsTxTime);
340 READWRITE(nTimeReceived);
341 READWRITE(fFromMe);
342 READWRITE(fSpent);
344 if (ser_action.ForRead())
346 strFromAccount = mapValue["fromaccount"];
348 ReadOrderPos(nOrderPos, mapValue);
350 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
353 mapValue.erase("fromaccount");
354 mapValue.erase("version");
355 mapValue.erase("spent");
356 mapValue.erase("n");
357 mapValue.erase("timesmart");
360 //! make sure balances are recalculated
361 void MarkDirty()
363 fCreditCached = false;
364 fAvailableCreditCached = false;
365 fWatchDebitCached = false;
366 fWatchCreditCached = false;
367 fAvailableWatchCreditCached = false;
368 fImmatureWatchCreditCached = false;
369 fDebitCached = false;
370 fChangeCached = false;
373 void BindWallet(CWallet *pwalletIn)
375 pwallet = pwalletIn;
376 MarkDirty();
379 //! filter decides which addresses will count towards the debit
380 CAmount GetDebit(const isminefilter& filter) const;
381 CAmount GetCredit(const isminefilter& filter) const;
382 CAmount GetImmatureCredit(bool fUseCache=true) const;
383 CAmount GetAvailableCredit(bool fUseCache=true) const;
384 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
385 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
386 CAmount GetChange() const;
388 void GetAmounts(std::list<COutputEntry>& listReceived,
389 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
391 void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
392 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
394 bool IsFromMe(const isminefilter& filter) const
396 return (GetDebit(filter) > 0);
399 // True if only scriptSigs are different
400 bool IsEquivalentTo(const CWalletTx& tx) const;
402 bool InMempool() const;
403 bool IsTrusted() const;
405 int64_t GetTxTime() const;
406 int GetRequestCount() const;
408 bool RelayWalletTransaction(CConnman* connman);
410 std::set<uint256> GetConflicts() const;
416 class COutput
418 public:
419 const CWalletTx *tx;
420 int i;
421 int nDepth;
422 bool fSpendable;
423 bool fSolvable;
425 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn)
427 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn;
430 std::string ToString() const;
436 /** Private key that includes an expiration date in case it never gets used. */
437 class CWalletKey
439 public:
440 CPrivKey vchPrivKey;
441 int64_t nTimeCreated;
442 int64_t nTimeExpires;
443 std::string strComment;
444 //! todo: add something to note what created it (user, getnewaddress, change)
445 //! maybe should have a map<string, string> property map
447 CWalletKey(int64_t nExpires=0);
449 ADD_SERIALIZE_METHODS;
451 template <typename Stream, typename Operation>
452 inline void SerializationOp(Stream& s, Operation ser_action) {
453 int nVersion = s.GetVersion();
454 if (!(s.GetType() & SER_GETHASH))
455 READWRITE(nVersion);
456 READWRITE(vchPrivKey);
457 READWRITE(nTimeCreated);
458 READWRITE(nTimeExpires);
459 READWRITE(LIMITED_STRING(strComment, 65536));
464 * Internal transfers.
465 * Database key is acentry<account><counter>.
467 class CAccountingEntry
469 public:
470 std::string strAccount;
471 CAmount nCreditDebit;
472 int64_t nTime;
473 std::string strOtherAccount;
474 std::string strComment;
475 mapValue_t mapValue;
476 int64_t nOrderPos; //!< position in ordered transaction list
477 uint64_t nEntryNo;
479 CAccountingEntry()
481 SetNull();
484 void SetNull()
486 nCreditDebit = 0;
487 nTime = 0;
488 strAccount.clear();
489 strOtherAccount.clear();
490 strComment.clear();
491 nOrderPos = -1;
492 nEntryNo = 0;
495 ADD_SERIALIZE_METHODS;
497 template <typename Stream, typename Operation>
498 inline void SerializationOp(Stream& s, Operation ser_action) {
499 int nVersion = s.GetVersion();
500 if (!(s.GetType() & SER_GETHASH))
501 READWRITE(nVersion);
502 //! Note: strAccount is serialized as part of the key, not here.
503 READWRITE(nCreditDebit);
504 READWRITE(nTime);
505 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
507 if (!ser_action.ForRead())
509 WriteOrderPos(nOrderPos, mapValue);
511 if (!(mapValue.empty() && _ssExtra.empty()))
513 CDataStream ss(s.GetType(), s.GetVersion());
514 ss.insert(ss.begin(), '\0');
515 ss << mapValue;
516 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
517 strComment.append(ss.str());
521 READWRITE(LIMITED_STRING(strComment, 65536));
523 size_t nSepPos = strComment.find("\0", 0, 1);
524 if (ser_action.ForRead())
526 mapValue.clear();
527 if (std::string::npos != nSepPos)
529 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
530 ss >> mapValue;
531 _ssExtra = std::vector<char>(ss.begin(), ss.end());
533 ReadOrderPos(nOrderPos, mapValue);
535 if (std::string::npos != nSepPos)
536 strComment.erase(nSepPos);
538 mapValue.erase("n");
541 private:
542 std::vector<char> _ssExtra;
546 /**
547 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
548 * and provides the ability to create new transactions.
550 class CWallet : public CCryptoKeyStore, public CValidationInterface
552 private:
554 * Select a set of coins such that nValueRet >= nTargetValue and at least
555 * all coins from coinControl are selected; Never select unconfirmed coins
556 * if they are not ours
558 bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL) const;
560 CWalletDB *pwalletdbEncryption;
562 //! the current wallet version: clients below this version are not able to load the wallet
563 int nWalletVersion;
565 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
566 int nWalletMaxVersion;
568 int64_t nNextResend;
569 int64_t nLastResend;
570 bool fBroadcastTransactions;
573 * Used to keep track of spent outpoints, and
574 * detect and report conflicts (double-spends or
575 * mutated transactions where the mutant gets mined).
577 typedef std::multimap<COutPoint, uint256> TxSpends;
578 TxSpends mapTxSpends;
579 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
580 void AddToSpends(const uint256& wtxid);
582 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
583 void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
585 void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
587 /* the HD chain data model (external chain counters) */
588 CHDChain hdChain;
590 bool fFileBacked;
592 std::set<int64_t> setKeyPool;
593 public:
595 * Main wallet lock.
596 * This lock protects all the fields added by CWallet
597 * except for:
598 * fFileBacked (immutable after instantiation)
599 * strWalletFile (immutable after instantiation)
601 mutable CCriticalSection cs_wallet;
603 std::string strWalletFile;
605 void LoadKeyPool(int nIndex, const CKeyPool &keypool)
607 setKeyPool.insert(nIndex);
609 // If no metadata exists yet, create a default with the pool key's
610 // creation time. Note that this may be overwritten by actually
611 // stored metadata for that key later, which is fine.
612 CKeyID keyid = keypool.vchPubKey.GetID();
613 if (mapKeyMetadata.count(keyid) == 0)
614 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
617 std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
619 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
620 MasterKeyMap mapMasterKeys;
621 unsigned int nMasterKeyMaxID;
623 CWallet()
625 SetNull();
628 CWallet(const std::string& strWalletFileIn)
630 SetNull();
632 strWalletFile = strWalletFileIn;
633 fFileBacked = true;
636 ~CWallet()
638 delete pwalletdbEncryption;
639 pwalletdbEncryption = NULL;
642 void SetNull()
644 nWalletVersion = FEATURE_BASE;
645 nWalletMaxVersion = FEATURE_BASE;
646 fFileBacked = false;
647 nMasterKeyMaxID = 0;
648 pwalletdbEncryption = NULL;
649 nOrderPosNext = 0;
650 nNextResend = 0;
651 nLastResend = 0;
652 nTimeFirstKey = 0;
653 fBroadcastTransactions = false;
656 std::map<uint256, CWalletTx> mapWallet;
657 std::list<CAccountingEntry> laccentries;
659 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
660 typedef std::multimap<int64_t, TxPair > TxItems;
661 TxItems wtxOrdered;
663 int64_t nOrderPosNext;
664 std::map<uint256, int> mapRequestCount;
666 std::map<CTxDestination, CAddressBookData> mapAddressBook;
668 CPubKey vchDefaultKey;
670 std::set<COutPoint> setLockedCoins;
672 int64_t nTimeFirstKey;
674 const CWalletTx* GetWalletTx(const uint256& hash) const;
676 //! check whether we are allowed to upgrade (or already support) to the named feature
677 bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
680 * populate vCoins with vector of available COutputs.
682 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false) const;
685 * Shuffle and select coins until nTargetValue is reached while avoiding
686 * small change; This method is stochastic for some inputs and upon
687 * completion the coin set and corresponding actual target value is
688 * assembled
690 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;
692 bool IsSpent(const uint256& hash, unsigned int n) const;
694 bool IsLockedCoin(uint256 hash, unsigned int n) const;
695 void LockCoin(const COutPoint& output);
696 void UnlockCoin(const COutPoint& output);
697 void UnlockAllCoins();
698 void ListLockedCoins(std::vector<COutPoint>& vOutpts);
701 * keystore implementation
702 * Generate a new key
704 CPubKey GenerateNewKey();
705 void DeriveNewChildKey(CKeyMetadata& metadata, CKey& secret);
706 //! Adds a key to the store, and saves it to disk.
707 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
708 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
709 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
710 //! Load metadata (used by LoadWallet)
711 bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
713 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
715 //! Adds an encrypted key to the store, and saves it to disk.
716 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
717 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
718 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
719 bool AddCScript(const CScript& redeemScript);
720 bool LoadCScript(const CScript& redeemScript);
722 //! Adds a destination data tuple to the store, and saves it to disk
723 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
724 //! Erases a destination data tuple in the store and on disk
725 bool EraseDestData(const CTxDestination &dest, const std::string &key);
726 //! Adds a destination data tuple to the store, without saving it to disk
727 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
728 //! Look up a destination data tuple in the store, return true if found false otherwise
729 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
731 //! Adds a watch-only address to the store, and saves it to disk.
732 bool AddWatchOnly(const CScript &dest);
733 bool RemoveWatchOnly(const CScript &dest);
734 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
735 bool LoadWatchOnly(const CScript &dest);
737 bool Unlock(const SecureString& strWalletPassphrase);
738 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
739 bool EncryptWallet(const SecureString& strWalletPassphrase);
741 void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
743 /**
744 * Increment the next transaction order id
745 * @return next transaction order id
747 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
748 DBErrors ReorderTransactions();
749 bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
750 bool GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew = false);
752 void MarkDirty();
753 bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
754 bool LoadToWallet(const CWalletTx& wtxIn);
755 void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock);
756 bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
757 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
758 void ReacceptWalletTransactions();
759 void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman);
760 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
761 CAmount GetBalance() const;
762 CAmount GetUnconfirmedBalance() const;
763 CAmount GetImmatureBalance() const;
764 CAmount GetWatchOnlyBalance() const;
765 CAmount GetUnconfirmedWatchOnlyBalance() const;
766 CAmount GetImmatureWatchOnlyBalance() const;
769 * Insert additional inputs into the transaction by
770 * calling CreateTransaction();
772 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const CTxDestination& destChange = CNoDestination());
775 * Create a new transaction paying the recipients with a set of coins
776 * selected by SelectCoins(); Also create the change output, when needed
777 * @note passing nChangePosInOut as -1 will result in setting a random position
779 bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
780 std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true);
781 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
783 void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
784 bool AddAccountingEntry(const CAccountingEntry&);
785 bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
787 static CFeeRate minTxFee;
788 static CFeeRate fallbackFee;
790 * Estimate the minimum fee considering user set parameters
791 * and the required fee
793 static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
795 * Return the minimum required fee taking into account the
796 * floating relay fee and user set minimum transaction fee
798 static CAmount GetRequiredFee(unsigned int nTxBytes);
800 bool NewKeyPool();
801 bool TopUpKeyPool(unsigned int kpSize = 0);
802 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool);
803 void KeepKey(int64_t nIndex);
804 void ReturnKey(int64_t nIndex);
805 bool GetKeyFromPool(CPubKey &key);
806 int64_t GetOldestKeyPoolTime();
807 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
809 std::set< std::set<CTxDestination> > GetAddressGroupings();
810 std::map<CTxDestination, CAmount> GetAddressBalances();
812 CAmount GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter);
813 CAmount GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter);
814 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
816 isminetype IsMine(const CTxIn& txin) const;
817 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
818 isminetype IsMine(const CTxOut& txout) const;
819 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
820 bool IsChange(const CTxOut& txout) const;
821 CAmount GetChange(const CTxOut& txout) const;
822 bool IsMine(const CTransaction& tx) const;
823 /** should probably be renamed to IsRelevantToMe */
824 bool IsFromMe(const CTransaction& tx) const;
825 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
826 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
827 CAmount GetChange(const CTransaction& tx) const;
828 void SetBestChain(const CBlockLocator& loc);
830 DBErrors LoadWallet(bool& fFirstRunRet);
831 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
832 DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut);
834 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
836 bool DelAddressBook(const CTxDestination& address);
838 void UpdatedTransaction(const uint256 &hashTx);
840 void Inventory(const uint256 &hash)
843 LOCK(cs_wallet);
844 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
845 if (mi != mapRequestCount.end())
846 (*mi).second++;
850 void GetScriptForMining(boost::shared_ptr<CReserveScript> &script);
851 void ResetRequestCount(const uint256 &hash)
853 LOCK(cs_wallet);
854 mapRequestCount[hash] = 0;
857 unsigned int GetKeyPoolSize()
859 AssertLockHeld(cs_wallet); // setKeyPool
860 return setKeyPool.size();
863 bool SetDefaultKey(const CPubKey &vchPubKey);
865 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
866 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
868 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
869 bool SetMaxVersion(int nVersion);
871 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
872 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
874 //! Get wallet transactions that conflict with given transaction (spend same outputs)
875 std::set<uint256> GetConflicts(const uint256& txid) const;
877 //! Flush wallet (bitdb flush)
878 void Flush(bool shutdown=false);
880 //! Verify the wallet database and perform salvage if required
881 static bool Verify();
883 /**
884 * Address book entry changed.
885 * @note called with lock cs_wallet held.
887 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
888 &address, const std::string &label, bool isMine,
889 const std::string &purpose,
890 ChangeType status)> NotifyAddressBookChanged;
892 /**
893 * Wallet transaction added, removed or updated.
894 * @note called with lock cs_wallet held.
896 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
897 ChangeType status)> NotifyTransactionChanged;
899 /** Show progress e.g. for rescan */
900 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
902 /** Watch-only address added */
903 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
905 /** Inquire whether this wallet broadcasts transactions. */
906 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
907 /** Set whether this wallet broadcasts transactions. */
908 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
910 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
911 bool AbandonTransaction(const uint256& hashTx);
913 /* Returns the wallets help message */
914 static std::string GetWalletHelpString(bool showDebug);
916 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
917 static bool InitLoadWallet();
920 * Wallet post-init setup
921 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
923 void postInitProcess(boost::thread_group& threadGroup);
925 /* Wallets parameter interaction */
926 static bool ParameterInteraction();
928 bool BackupWallet(const std::string& strDest);
930 /* Set the HD chain model (chain child index counters) */
931 bool SetHDChain(const CHDChain& chain, bool memonly);
932 const CHDChain& GetHDChain() { return hdChain; }
934 /* Returns true if HD is enabled */
935 bool IsHDEnabled();
937 /* Generates a new HD master key (will not be activated) */
938 CPubKey GenerateNewHDMasterKey();
940 /* Set the current HD master key (will reset the chain child index counters) */
941 bool SetHDMasterKey(const CPubKey& key);
944 /** A key allocated from the key pool. */
945 class CReserveKey : public CReserveScript
947 protected:
948 CWallet* pwallet;
949 int64_t nIndex;
950 CPubKey vchPubKey;
951 public:
952 CReserveKey(CWallet* pwalletIn)
954 nIndex = -1;
955 pwallet = pwalletIn;
958 ~CReserveKey()
960 ReturnKey();
963 void ReturnKey();
964 bool GetReservedKey(CPubKey &pubkey);
965 void KeepKey();
966 void KeepScript() { KeepKey(); }
970 /**
971 * Account information.
972 * Stored in wallet with key "acc"+string account name.
974 class CAccount
976 public:
977 CPubKey vchPubKey;
979 CAccount()
981 SetNull();
984 void SetNull()
986 vchPubKey = CPubKey();
989 ADD_SERIALIZE_METHODS;
991 template <typename Stream, typename Operation>
992 inline void SerializationOp(Stream& s, Operation ser_action) {
993 int nVersion = s.GetVersion();
994 if (!(s.GetType() & SER_GETHASH))
995 READWRITE(nVersion);
996 READWRITE(vchPubKey);
1000 #endif // BITCOIN_WALLET_WALLET_H