doc: Add historical release notes for 0.15.1
[bitcoinplatinum.git] / src / wallet / wallet.h
blobdb2861c04307cae9b1deaa09c3dc054969a12766
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 "policy/feerate.h"
11 #include "streams.h"
12 #include "tinyformat.h"
13 #include "ui_interface.h"
14 #include "utilstrencodings.h"
15 #include "validationinterface.h"
16 #include "script/ismine.h"
17 #include "script/sign.h"
18 #include "wallet/crypter.h"
19 #include "wallet/walletdb.h"
20 #include "wallet/rpcwallet.h"
22 #include <algorithm>
23 #include <atomic>
24 #include <map>
25 #include <set>
26 #include <stdexcept>
27 #include <stdint.h>
28 #include <string>
29 #include <utility>
30 #include <vector>
32 typedef CWallet* CWalletRef;
33 extern std::vector<CWalletRef> vpwallets;
35 /**
36 * Settings
38 extern CFeeRate payTxFee;
39 extern unsigned int nTxConfirmTarget;
40 extern bool bSpendZeroConfChange;
41 extern bool fWalletRbf;
43 static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
44 //! -paytxfee default
45 static const CAmount DEFAULT_TRANSACTION_FEE = 0;
46 //! -fallbackfee default
47 static const CAmount DEFAULT_FALLBACK_FEE = 20000;
48 //! -m_discard_rate default
49 static const CAmount DEFAULT_DISCARD_FEE = 10000;
50 //! -mintxfee default
51 static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
52 //! minimum recommended increment for BIP 125 replacement txs
53 static const CAmount WALLET_INCREMENTAL_RELAY_FEE = 5000;
54 //! target minimum change amount
55 static const CAmount MIN_CHANGE = CENT;
56 //! final minimum change amount after paying for fees
57 static const CAmount MIN_FINAL_CHANGE = MIN_CHANGE/2;
58 //! Default for -spendzeroconfchange
59 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
60 //! Default for -walletrejectlongchains
61 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
62 //! -txconfirmtarget default
63 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
64 //! -walletrbf default
65 static const bool DEFAULT_WALLET_RBF = false;
66 static const bool DEFAULT_WALLETBROADCAST = true;
67 static const bool DEFAULT_DISABLE_WALLET = false;
69 extern const char * DEFAULT_WALLET_DAT;
71 static const int64_t TIMESTAMP_MIN = 0;
73 class CBlockIndex;
74 class CCoinControl;
75 class COutput;
76 class CReserveKey;
77 class CScript;
78 class CScheduler;
79 class CTxMemPool;
80 class CBlockPolicyEstimator;
81 class CWalletTx;
82 struct FeeCalculation;
83 enum class FeeEstimateMode;
85 /** (client) version numbers for particular wallet features */
86 enum WalletFeature
88 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getwalletinfo's clientversion output)
90 FEATURE_WALLETCRYPT = 40000, // wallet encryption
91 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
93 FEATURE_HD = 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
95 FEATURE_HD_SPLIT = 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
97 FEATURE_NO_DEFAULT_KEY = 159900, // Wallet without a default key written
99 FEATURE_LATEST = FEATURE_COMPRPUBKEY // HD is optional, use FEATURE_COMPRPUBKEY as latest version
103 /** A key pool entry */
104 class CKeyPool
106 public:
107 int64_t nTime;
108 CPubKey vchPubKey;
109 bool fInternal; // for change outputs
111 CKeyPool();
112 CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn);
114 ADD_SERIALIZE_METHODS;
116 template <typename Stream, typename Operation>
117 inline void SerializationOp(Stream& s, Operation ser_action) {
118 int nVersion = s.GetVersion();
119 if (!(s.GetType() & SER_GETHASH))
120 READWRITE(nVersion);
121 READWRITE(nTime);
122 READWRITE(vchPubKey);
123 if (ser_action.ForRead()) {
124 try {
125 READWRITE(fInternal);
127 catch (std::ios_base::failure&) {
128 /* flag as external address if we can't read the internal boolean
129 (this will be the case for any wallet before the HD chain split version) */
130 fInternal = false;
133 else {
134 READWRITE(fInternal);
139 /** Address book data */
140 class CAddressBookData
142 public:
143 std::string name;
144 std::string purpose;
146 CAddressBookData() : purpose("unknown") {}
148 typedef std::map<std::string, std::string> StringMap;
149 StringMap destdata;
152 struct CRecipient
154 CScript scriptPubKey;
155 CAmount nAmount;
156 bool fSubtractFeeFromAmount;
159 typedef std::map<std::string, std::string> mapValue_t;
162 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
164 if (!mapValue.count("n"))
166 nOrderPos = -1; // TODO: calculate elsewhere
167 return;
169 nOrderPos = atoi64(mapValue["n"].c_str());
173 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
175 if (nOrderPos == -1)
176 return;
177 mapValue["n"] = i64tostr(nOrderPos);
180 struct COutputEntry
182 CTxDestination destination;
183 CAmount amount;
184 int vout;
187 /** A transaction with a merkle branch linking it to the block chain. */
188 class CMerkleTx
190 private:
191 /** Constant used in hashBlock to indicate tx has been abandoned */
192 static const uint256 ABANDON_HASH;
194 public:
195 CTransactionRef tx;
196 uint256 hashBlock;
198 /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
199 * block in the chain we know this or any in-wallet dependency conflicts
200 * with. Older clients interpret nIndex == -1 as unconfirmed for backward
201 * compatibility.
203 int nIndex;
205 CMerkleTx()
207 SetTx(MakeTransactionRef());
208 Init();
211 explicit CMerkleTx(CTransactionRef arg)
213 SetTx(std::move(arg));
214 Init();
217 void Init()
219 hashBlock = uint256();
220 nIndex = -1;
223 void SetTx(CTransactionRef arg)
225 tx = std::move(arg);
228 ADD_SERIALIZE_METHODS;
230 template <typename Stream, typename Operation>
231 inline void SerializationOp(Stream& s, Operation ser_action) {
232 std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
233 READWRITE(tx);
234 READWRITE(hashBlock);
235 READWRITE(vMerkleBranch);
236 READWRITE(nIndex);
239 void SetMerkleBranch(const CBlockIndex* pIndex, int posInBlock);
242 * Return depth of transaction in blockchain:
243 * <0 : conflicts with a transaction this deep in the blockchain
244 * 0 : in memory pool, waiting to be included in a block
245 * >=1 : this many blocks deep in the main chain
247 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
248 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
249 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; }
250 int GetBlocksToMaturity() const;
251 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
252 bool AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state);
253 bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
254 bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
255 void setAbandoned() { hashBlock = ABANDON_HASH; }
257 const uint256& GetHash() const { return tx->GetHash(); }
258 bool IsCoinBase() const { return tx->IsCoinBase(); }
261 /**
262 * A transaction with a bunch of additional info that only the owner cares about.
263 * It includes any unrecorded transactions needed to link it back to the block chain.
265 class CWalletTx : public CMerkleTx
267 private:
268 const CWallet* pwallet;
270 public:
272 * Key/value map with information about the transaction.
274 * The following keys can be read and written through the map and are
275 * serialized in the wallet database:
277 * "comment", "to" - comment strings provided to sendtoaddress,
278 * sendfrom, sendmany wallet RPCs
279 * "replaces_txid" - txid (as HexStr) of transaction replaced by
280 * bumpfee on transaction created by bumpfee
281 * "replaced_by_txid" - txid (as HexStr) of transaction created by
282 * bumpfee on transaction replaced by bumpfee
283 * "from", "message" - obsolete fields that could be set in UI prior to
284 * 2011 (removed in commit 4d9b223)
286 * The following keys are serialized in the wallet database, but shouldn't
287 * be read or written through the map (they will be temporarily added and
288 * removed from the map during serialization):
290 * "fromaccount" - serialized strFromAccount value
291 * "n" - serialized nOrderPos value
292 * "timesmart" - serialized nTimeSmart value
293 * "spent" - serialized vfSpent value that existed prior to
294 * 2014 (removed in commit 93a18a3)
296 mapValue_t mapValue;
297 std::vector<std::pair<std::string, std::string> > vOrderForm;
298 unsigned int fTimeReceivedIsTxTime;
299 unsigned int nTimeReceived; //!< time received by this node
301 * Stable timestamp that never changes, and reflects the order a transaction
302 * was added to the wallet. Timestamp is based on the block time for a
303 * transaction added as part of a block, or else the time when the
304 * transaction was received if it wasn't part of a block, with the timestamp
305 * adjusted in both cases so timestamp order matches the order transactions
306 * were added to the wallet. More details can be found in
307 * CWallet::ComputeTimeSmart().
309 unsigned int nTimeSmart;
311 * From me flag is set to 1 for transactions that were created by the wallet
312 * on this bitcoin node, and set to 0 for transactions that were created
313 * externally and came in through the network or sendrawtransaction RPC.
315 char fFromMe;
316 std::string strFromAccount;
317 int64_t nOrderPos; //!< position in ordered transaction list
319 // memory only
320 mutable bool fDebitCached;
321 mutable bool fCreditCached;
322 mutable bool fImmatureCreditCached;
323 mutable bool fAvailableCreditCached;
324 mutable bool fWatchDebitCached;
325 mutable bool fWatchCreditCached;
326 mutable bool fImmatureWatchCreditCached;
327 mutable bool fAvailableWatchCreditCached;
328 mutable bool fChangeCached;
329 mutable CAmount nDebitCached;
330 mutable CAmount nCreditCached;
331 mutable CAmount nImmatureCreditCached;
332 mutable CAmount nAvailableCreditCached;
333 mutable CAmount nWatchDebitCached;
334 mutable CAmount nWatchCreditCached;
335 mutable CAmount nImmatureWatchCreditCached;
336 mutable CAmount nAvailableWatchCreditCached;
337 mutable CAmount nChangeCached;
339 CWalletTx()
341 Init(nullptr);
344 CWalletTx(const CWallet* pwalletIn, CTransactionRef arg) : CMerkleTx(std::move(arg))
346 Init(pwalletIn);
349 void Init(const CWallet* pwalletIn)
351 pwallet = pwalletIn;
352 mapValue.clear();
353 vOrderForm.clear();
354 fTimeReceivedIsTxTime = false;
355 nTimeReceived = 0;
356 nTimeSmart = 0;
357 fFromMe = false;
358 strFromAccount.clear();
359 fDebitCached = false;
360 fCreditCached = false;
361 fImmatureCreditCached = false;
362 fAvailableCreditCached = false;
363 fWatchDebitCached = false;
364 fWatchCreditCached = false;
365 fImmatureWatchCreditCached = false;
366 fAvailableWatchCreditCached = false;
367 fChangeCached = false;
368 nDebitCached = 0;
369 nCreditCached = 0;
370 nImmatureCreditCached = 0;
371 nAvailableCreditCached = 0;
372 nWatchDebitCached = 0;
373 nWatchCreditCached = 0;
374 nAvailableWatchCreditCached = 0;
375 nImmatureWatchCreditCached = 0;
376 nChangeCached = 0;
377 nOrderPos = -1;
380 ADD_SERIALIZE_METHODS;
382 template <typename Stream, typename Operation>
383 inline void SerializationOp(Stream& s, Operation ser_action) {
384 if (ser_action.ForRead())
385 Init(nullptr);
386 char fSpent = false;
388 if (!ser_action.ForRead())
390 mapValue["fromaccount"] = strFromAccount;
392 WriteOrderPos(nOrderPos, mapValue);
394 if (nTimeSmart)
395 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
398 READWRITE(*(CMerkleTx*)this);
399 std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
400 READWRITE(vUnused);
401 READWRITE(mapValue);
402 READWRITE(vOrderForm);
403 READWRITE(fTimeReceivedIsTxTime);
404 READWRITE(nTimeReceived);
405 READWRITE(fFromMe);
406 READWRITE(fSpent);
408 if (ser_action.ForRead())
410 strFromAccount = mapValue["fromaccount"];
412 ReadOrderPos(nOrderPos, mapValue);
414 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
417 mapValue.erase("fromaccount");
418 mapValue.erase("spent");
419 mapValue.erase("n");
420 mapValue.erase("timesmart");
423 //! make sure balances are recalculated
424 void MarkDirty()
426 fCreditCached = false;
427 fAvailableCreditCached = false;
428 fImmatureCreditCached = false;
429 fWatchDebitCached = false;
430 fWatchCreditCached = false;
431 fAvailableWatchCreditCached = false;
432 fImmatureWatchCreditCached = false;
433 fDebitCached = false;
434 fChangeCached = false;
437 void BindWallet(CWallet *pwalletIn)
439 pwallet = pwalletIn;
440 MarkDirty();
443 //! filter decides which addresses will count towards the debit
444 CAmount GetDebit(const isminefilter& filter) const;
445 CAmount GetCredit(const isminefilter& filter) const;
446 CAmount GetImmatureCredit(bool fUseCache=true) const;
447 CAmount GetAvailableCredit(bool fUseCache=true) const;
448 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
449 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
450 CAmount GetChange() const;
452 void GetAmounts(std::list<COutputEntry>& listReceived,
453 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
455 bool IsFromMe(const isminefilter& filter) const
457 return (GetDebit(filter) > 0);
460 // True if only scriptSigs are different
461 bool IsEquivalentTo(const CWalletTx& tx) const;
463 bool InMempool() const;
464 bool IsTrusted() const;
466 int64_t GetTxTime() const;
467 int GetRequestCount() const;
469 // RelayWalletTransaction may only be called if fBroadcastTransactions!
470 bool RelayWalletTransaction(CConnman* connman);
472 std::set<uint256> GetConflicts() const;
476 class CInputCoin {
477 public:
478 CInputCoin(const CWalletTx* walletTx, unsigned int i)
480 if (!walletTx)
481 throw std::invalid_argument("walletTx should not be null");
482 if (i >= walletTx->tx->vout.size())
483 throw std::out_of_range("The output index is out of range");
485 outpoint = COutPoint(walletTx->GetHash(), i);
486 txout = walletTx->tx->vout[i];
489 COutPoint outpoint;
490 CTxOut txout;
492 bool operator<(const CInputCoin& rhs) const {
493 return outpoint < rhs.outpoint;
496 bool operator!=(const CInputCoin& rhs) const {
497 return outpoint != rhs.outpoint;
500 bool operator==(const CInputCoin& rhs) const {
501 return outpoint == rhs.outpoint;
505 class COutput
507 public:
508 const CWalletTx *tx;
509 int i;
510 int nDepth;
512 /** Whether we have the private keys to spend this output */
513 bool fSpendable;
515 /** Whether we know how to spend this output, ignoring the lack of keys */
516 bool fSolvable;
519 * Whether this output is considered safe to spend. Unconfirmed transactions
520 * from outside keys and unconfirmed replacement transactions are considered
521 * unsafe and will not be used to fund new spending transactions.
523 bool fSafe;
525 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn)
527 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn;
530 std::string ToString() const;
536 /** Private key that includes an expiration date in case it never gets used. */
537 class CWalletKey
539 public:
540 CPrivKey vchPrivKey;
541 int64_t nTimeCreated;
542 int64_t nTimeExpires;
543 std::string strComment;
544 //! todo: add something to note what created it (user, getnewaddress, change)
545 //! maybe should have a map<string, string> property map
547 explicit CWalletKey(int64_t nExpires=0);
549 ADD_SERIALIZE_METHODS;
551 template <typename Stream, typename Operation>
552 inline void SerializationOp(Stream& s, Operation ser_action) {
553 int nVersion = s.GetVersion();
554 if (!(s.GetType() & SER_GETHASH))
555 READWRITE(nVersion);
556 READWRITE(vchPrivKey);
557 READWRITE(nTimeCreated);
558 READWRITE(nTimeExpires);
559 READWRITE(LIMITED_STRING(strComment, 65536));
564 * Internal transfers.
565 * Database key is acentry<account><counter>.
567 class CAccountingEntry
569 public:
570 std::string strAccount;
571 CAmount nCreditDebit;
572 int64_t nTime;
573 std::string strOtherAccount;
574 std::string strComment;
575 mapValue_t mapValue;
576 int64_t nOrderPos; //!< position in ordered transaction list
577 uint64_t nEntryNo;
579 CAccountingEntry()
581 SetNull();
584 void SetNull()
586 nCreditDebit = 0;
587 nTime = 0;
588 strAccount.clear();
589 strOtherAccount.clear();
590 strComment.clear();
591 nOrderPos = -1;
592 nEntryNo = 0;
595 ADD_SERIALIZE_METHODS;
597 template <typename Stream, typename Operation>
598 inline void SerializationOp(Stream& s, Operation ser_action) {
599 int nVersion = s.GetVersion();
600 if (!(s.GetType() & SER_GETHASH))
601 READWRITE(nVersion);
602 //! Note: strAccount is serialized as part of the key, not here.
603 READWRITE(nCreditDebit);
604 READWRITE(nTime);
605 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
607 if (!ser_action.ForRead())
609 WriteOrderPos(nOrderPos, mapValue);
611 if (!(mapValue.empty() && _ssExtra.empty()))
613 CDataStream ss(s.GetType(), s.GetVersion());
614 ss.insert(ss.begin(), '\0');
615 ss << mapValue;
616 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
617 strComment.append(ss.str());
621 READWRITE(LIMITED_STRING(strComment, 65536));
623 size_t nSepPos = strComment.find("\0", 0, 1);
624 if (ser_action.ForRead())
626 mapValue.clear();
627 if (std::string::npos != nSepPos)
629 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
630 ss >> mapValue;
631 _ssExtra = std::vector<char>(ss.begin(), ss.end());
633 ReadOrderPos(nOrderPos, mapValue);
635 if (std::string::npos != nSepPos)
636 strComment.erase(nSepPos);
638 mapValue.erase("n");
641 private:
642 std::vector<char> _ssExtra;
646 /**
647 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
648 * and provides the ability to create new transactions.
650 class CWallet final : public CCryptoKeyStore, public CValidationInterface
652 private:
653 static std::atomic<bool> fFlushScheduled;
654 std::atomic<bool> fAbortRescan;
655 std::atomic<bool> fScanningWallet;
658 * Select a set of coins such that nValueRet >= nTargetValue and at least
659 * all coins from coinControl are selected; Never select unconfirmed coins
660 * if they are not ours
662 bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = nullptr) const;
664 CWalletDB *pwalletdbEncryption;
666 //! the current wallet version: clients below this version are not able to load the wallet
667 int nWalletVersion;
669 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
670 int nWalletMaxVersion;
672 int64_t nNextResend;
673 int64_t nLastResend;
674 bool fBroadcastTransactions;
677 * Used to keep track of spent outpoints, and
678 * detect and report conflicts (double-spends or
679 * mutated transactions where the mutant gets mined).
681 typedef std::multimap<COutPoint, uint256> TxSpends;
682 TxSpends mapTxSpends;
683 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
684 void AddToSpends(const uint256& wtxid);
686 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
687 void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
689 void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
691 /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected.
692 * Should be called with pindexBlock and posInBlock if this is for a transaction that is included in a block. */
693 void SyncTransaction(const CTransactionRef& tx, const CBlockIndex *pindex = nullptr, int posInBlock = 0);
695 /* the HD chain data model (external chain counters) */
696 CHDChain hdChain;
698 /* HD derive new child key (on internal or external chain) */
699 void DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal = false);
701 std::set<int64_t> setInternalKeyPool;
702 std::set<int64_t> setExternalKeyPool;
703 int64_t m_max_keypool_index;
704 std::map<CKeyID, int64_t> m_pool_key_to_index;
706 int64_t nTimeFirstKey;
709 * Private version of AddWatchOnly method which does not accept a
710 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
711 * the watch key did not previously have a timestamp associated with it.
712 * Because this is an inherited virtual method, it is accessible despite
713 * being marked private, but it is marked private anyway to encourage use
714 * of the other AddWatchOnly which accepts a timestamp and sets
715 * nTimeFirstKey more intelligently for more efficient rescans.
717 bool AddWatchOnly(const CScript& dest) override;
719 std::unique_ptr<CWalletDBWrapper> dbw;
721 public:
723 * Main wallet lock.
724 * This lock protects all the fields added by CWallet.
726 mutable CCriticalSection cs_wallet;
728 /** Get database handle used by this wallet. Ideally this function would
729 * not be necessary.
731 CWalletDBWrapper& GetDBHandle()
733 return *dbw;
736 /** Get a name for this wallet for logging/debugging purposes.
738 std::string GetName() const
740 if (dbw) {
741 return dbw->GetName();
742 } else {
743 return "dummy";
747 void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool);
749 // Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
750 // key metadata.
751 std::map<CTxDestination, CKeyMetadata> mapKeyMetadata;
753 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
754 MasterKeyMap mapMasterKeys;
755 unsigned int nMasterKeyMaxID;
757 // Create wallet with dummy database handle
758 CWallet(): dbw(new CWalletDBWrapper())
760 SetNull();
763 // Create wallet with passed-in database handle
764 explicit CWallet(std::unique_ptr<CWalletDBWrapper> dbw_in) : dbw(std::move(dbw_in))
766 SetNull();
769 ~CWallet()
771 delete pwalletdbEncryption;
772 pwalletdbEncryption = nullptr;
775 void SetNull()
777 nWalletVersion = FEATURE_BASE;
778 nWalletMaxVersion = FEATURE_BASE;
779 nMasterKeyMaxID = 0;
780 pwalletdbEncryption = nullptr;
781 nOrderPosNext = 0;
782 nAccountingEntryNumber = 0;
783 nNextResend = 0;
784 nLastResend = 0;
785 m_max_keypool_index = 0;
786 nTimeFirstKey = 0;
787 fBroadcastTransactions = false;
788 nRelockTime = 0;
789 fAbortRescan = false;
790 fScanningWallet = false;
793 std::map<uint256, CWalletTx> mapWallet;
794 std::list<CAccountingEntry> laccentries;
796 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
797 typedef std::multimap<int64_t, TxPair > TxItems;
798 TxItems wtxOrdered;
800 int64_t nOrderPosNext;
801 uint64_t nAccountingEntryNumber;
802 std::map<uint256, int> mapRequestCount;
804 std::map<CTxDestination, CAddressBookData> mapAddressBook;
806 std::set<COutPoint> setLockedCoins;
808 const CWalletTx* GetWalletTx(const uint256& hash) const;
810 //! check whether we are allowed to upgrade (or already support) to the named feature
811 bool CanSupportFeature(enum WalletFeature wf) const { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
814 * populate vCoins with vector of available COutputs.
816 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlySafe=true, const CCoinControl *coinControl = nullptr, const CAmount& nMinimumAmount = 1, const CAmount& nMaximumAmount = MAX_MONEY, const CAmount& nMinimumSumAmount = MAX_MONEY, const uint64_t& nMaximumCount = 0, const int& nMinDepth = 0, const int& nMaxDepth = 9999999) const;
819 * Return list of available coins and locked coins grouped by non-change output address.
821 std::map<CTxDestination, std::vector<COutput>> ListCoins() const;
824 * Find non-change parent output.
826 const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const;
829 * Shuffle and select coins until nTargetValue is reached while avoiding
830 * small change; This method is stochastic for some inputs and upon
831 * completion the coin set and corresponding actual target value is
832 * assembled
834 bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const;
836 bool IsSpent(const uint256& hash, unsigned int n) const;
838 bool IsLockedCoin(uint256 hash, unsigned int n) const;
839 void LockCoin(const COutPoint& output);
840 void UnlockCoin(const COutPoint& output);
841 void UnlockAllCoins();
842 void ListLockedCoins(std::vector<COutPoint>& vOutpts) const;
845 * Rescan abort properties
847 void AbortRescan() { fAbortRescan = true; }
848 bool IsAbortingRescan() { return fAbortRescan; }
849 bool IsScanning() { return fScanningWallet; }
852 * keystore implementation
853 * Generate a new key
855 CPubKey GenerateNewKey(CWalletDB& walletdb, bool internal = false);
856 //! Adds a key to the store, and saves it to disk.
857 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
858 bool AddKeyPubKeyWithDB(CWalletDB &walletdb,const CKey& key, const CPubKey &pubkey);
859 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
860 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
861 //! Load metadata (used by LoadWallet)
862 bool LoadKeyMetadata(const CTxDestination& pubKey, const CKeyMetadata &metadata);
864 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
865 void UpdateTimeFirstKey(int64_t nCreateTime);
867 //! Adds an encrypted key to the store, and saves it to disk.
868 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) override;
869 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
870 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
871 bool AddCScript(const CScript& redeemScript) override;
872 bool LoadCScript(const CScript& redeemScript);
874 //! Adds a destination data tuple to the store, and saves it to disk
875 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
876 //! Erases a destination data tuple in the store and on disk
877 bool EraseDestData(const CTxDestination &dest, const std::string &key);
878 //! Adds a destination data tuple to the store, without saving it to disk
879 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
880 //! Look up a destination data tuple in the store, return true if found false otherwise
881 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
882 //! Get all destination values matching a prefix.
883 std::vector<std::string> GetDestValues(const std::string& prefix) const;
885 //! Adds a watch-only address to the store, and saves it to disk.
886 bool AddWatchOnly(const CScript& dest, int64_t nCreateTime);
887 bool RemoveWatchOnly(const CScript &dest) override;
888 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
889 bool LoadWatchOnly(const CScript &dest);
891 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
892 int64_t nRelockTime;
894 bool Unlock(const SecureString& strWalletPassphrase);
895 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
896 bool EncryptWallet(const SecureString& strWalletPassphrase);
898 void GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const;
899 unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
901 /**
902 * Increment the next transaction order id
903 * @return next transaction order id
905 int64_t IncOrderPosNext(CWalletDB *pwalletdb = nullptr);
906 DBErrors ReorderTransactions();
907 bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
908 bool GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew = false);
910 void MarkDirty();
911 bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
912 bool LoadToWallet(const CWalletTx& wtxIn);
913 void TransactionAddedToMempool(const CTransactionRef& tx) override;
914 void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) override;
915 void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override;
916 bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
917 int64_t RescanFromTime(int64_t startTime, bool update);
918 CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate = false);
919 void ReacceptWalletTransactions();
920 void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) override;
921 // ResendWalletTransactionsBefore may only be called if fBroadcastTransactions!
922 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
923 CAmount GetBalance() const;
924 CAmount GetUnconfirmedBalance() const;
925 CAmount GetImmatureBalance() const;
926 CAmount GetWatchOnlyBalance() const;
927 CAmount GetUnconfirmedWatchOnlyBalance() const;
928 CAmount GetImmatureWatchOnlyBalance() const;
929 CAmount GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const;
930 CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
933 * Insert additional inputs into the transaction by
934 * calling CreateTransaction();
936 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
937 bool SignTransaction(CMutableTransaction& tx);
940 * Create a new transaction paying the recipients with a set of coins
941 * selected by SelectCoins(); Also create the change output, when needed
942 * @note passing nChangePosInOut as -1 will result in setting a random position
944 bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
945 std::string& strFailReason, const CCoinControl& coin_control, bool sign = true);
946 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
948 void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
949 bool AddAccountingEntry(const CAccountingEntry&);
950 bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
951 template <typename ContainerType>
952 bool DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const;
954 static CFeeRate minTxFee;
955 static CFeeRate fallbackFee;
956 static CFeeRate m_discard_rate;
958 bool NewKeyPool();
959 size_t KeypoolCountExternalKeys();
960 bool TopUpKeyPool(unsigned int kpSize = 0);
961 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
962 void KeepKey(int64_t nIndex);
963 void ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey);
964 bool GetKeyFromPool(CPubKey &key, bool internal = false);
965 int64_t GetOldestKeyPoolTime();
967 * Marks all keys in the keypool up to and including reserve_key as used.
969 void MarkReserveKeysAsUsed(int64_t keypool_id);
970 const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }
972 std::set< std::set<CTxDestination> > GetAddressGroupings();
973 std::map<CTxDestination, CAmount> GetAddressBalances();
975 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
977 isminetype IsMine(const CTxIn& txin) const;
979 * Returns amount of debit if the input matches the
980 * filter, otherwise returns 0
982 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
983 isminetype IsMine(const CTxOut& txout) const;
984 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
985 bool IsChange(const CTxOut& txout) const;
986 CAmount GetChange(const CTxOut& txout) const;
987 bool IsMine(const CTransaction& tx) const;
988 /** should probably be renamed to IsRelevantToMe */
989 bool IsFromMe(const CTransaction& tx) const;
990 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
991 /** Returns whether all of the inputs match the filter */
992 bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
993 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
994 CAmount GetChange(const CTransaction& tx) const;
995 void SetBestChain(const CBlockLocator& loc) override;
997 DBErrors LoadWallet(bool& fFirstRunRet);
998 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
999 DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut);
1001 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1003 bool DelAddressBook(const CTxDestination& address);
1005 const std::string& GetAccountName(const CScript& scriptPubKey) const;
1007 void Inventory(const uint256 &hash) override
1010 LOCK(cs_wallet);
1011 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
1012 if (mi != mapRequestCount.end())
1013 (*mi).second++;
1017 void GetScriptForMining(std::shared_ptr<CReserveScript> &script);
1019 unsigned int GetKeyPoolSize()
1021 AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool
1022 return setInternalKeyPool.size() + setExternalKeyPool.size();
1025 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1026 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = nullptr, bool fExplicit = false);
1028 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1029 bool SetMaxVersion(int nVersion);
1031 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1032 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1034 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1035 std::set<uint256> GetConflicts(const uint256& txid) const;
1037 //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
1038 bool HasWalletSpend(const uint256& txid) const;
1040 //! Flush wallet (bitdb flush)
1041 void Flush(bool shutdown=false);
1043 /**
1044 * Address book entry changed.
1045 * @note called with lock cs_wallet held.
1047 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1048 &address, const std::string &label, bool isMine,
1049 const std::string &purpose,
1050 ChangeType status)> NotifyAddressBookChanged;
1052 /**
1053 * Wallet transaction added, removed or updated.
1054 * @note called with lock cs_wallet held.
1056 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1057 ChangeType status)> NotifyTransactionChanged;
1059 /** Show progress e.g. for rescan */
1060 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1062 /** Watch-only address added */
1063 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1065 /** Inquire whether this wallet broadcasts transactions. */
1066 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1067 /** Set whether this wallet broadcasts transactions. */
1068 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1070 /** Return whether transaction can be abandoned */
1071 bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1073 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1074 bool AbandonTransaction(const uint256& hashTx);
1076 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1077 bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1079 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1080 static CWallet* CreateWalletFromFile(const std::string walletFile);
1083 * Wallet post-init setup
1084 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1086 void postInitProcess(CScheduler& scheduler);
1088 bool BackupWallet(const std::string& strDest);
1090 /* Set the HD chain model (chain child index counters) */
1091 bool SetHDChain(const CHDChain& chain, bool memonly);
1092 const CHDChain& GetHDChain() const { return hdChain; }
1094 /* Returns true if HD is enabled */
1095 bool IsHDEnabled() const;
1097 /* Generates a new HD master key (will not be activated) */
1098 CPubKey GenerateNewHDMasterKey();
1100 /* Set the current HD master key (will reset the chain child index counters)
1101 Sets the master key's version based on the current wallet version (so the
1102 caller must ensure the current wallet version is correct before calling
1103 this function). */
1104 bool SetHDMasterKey(const CPubKey& key);
1107 /** A key allocated from the key pool. */
1108 class CReserveKey final : public CReserveScript
1110 protected:
1111 CWallet* pwallet;
1112 int64_t nIndex;
1113 CPubKey vchPubKey;
1114 bool fInternal;
1115 public:
1116 explicit CReserveKey(CWallet* pwalletIn)
1118 nIndex = -1;
1119 pwallet = pwalletIn;
1120 fInternal = false;
1123 CReserveKey() = default;
1124 CReserveKey(const CReserveKey&) = delete;
1125 CReserveKey& operator=(const CReserveKey&) = delete;
1127 ~CReserveKey()
1129 ReturnKey();
1132 void ReturnKey();
1133 bool GetReservedKey(CPubKey &pubkey, bool internal = false);
1134 void KeepKey();
1135 void KeepScript() override { KeepKey(); }
1139 /**
1140 * Account information.
1141 * Stored in wallet with key "acc"+string account name.
1143 class CAccount
1145 public:
1146 CPubKey vchPubKey;
1148 CAccount()
1150 SetNull();
1153 void SetNull()
1155 vchPubKey = CPubKey();
1158 ADD_SERIALIZE_METHODS;
1160 template <typename Stream, typename Operation>
1161 inline void SerializationOp(Stream& s, Operation ser_action) {
1162 int nVersion = s.GetVersion();
1163 if (!(s.GetType() & SER_GETHASH))
1164 READWRITE(nVersion);
1165 READWRITE(vchPubKey);
1169 // Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
1170 // ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
1171 // so that each entry corresponds to each vIn, in order.
1172 template <typename ContainerType>
1173 bool CWallet::DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const
1175 // Fill in dummy signatures for fee calculation.
1176 int nIn = 0;
1177 for (const auto& coin : coins)
1179 const CScript& scriptPubKey = coin.txout.scriptPubKey;
1180 SignatureData sigdata;
1182 if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata))
1184 return false;
1185 } else {
1186 UpdateTransaction(txNew, nIn, sigdata);
1189 nIn++;
1191 return true;
1194 #endif // BITCOIN_WALLET_WALLET_H