Fix constness of ArgsManager methods
[bitcoinplatinum.git] / src / wallet / wallet.h
blob7ef2e6f1d8ead70a022430e1893ab922cd83c545
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;
68 //! if set, all keys will be derived by using BIP32
69 static const bool DEFAULT_USE_HD_WALLET = true;
71 extern const char * DEFAULT_WALLET_DAT;
73 static const int64_t TIMESTAMP_MIN = 0;
75 class CBlockIndex;
76 class CCoinControl;
77 class COutput;
78 class CReserveKey;
79 class CScript;
80 class CScheduler;
81 class CTxMemPool;
82 class CBlockPolicyEstimator;
83 class CWalletTx;
84 struct FeeCalculation;
85 enum class FeeEstimateMode;
87 /** (client) version numbers for particular wallet features */
88 enum WalletFeature
90 FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
92 FEATURE_WALLETCRYPT = 40000, // wallet encryption
93 FEATURE_COMPRPUBKEY = 60000, // compressed public keys
95 FEATURE_HD = 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
97 FEATURE_HD_SPLIT = 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
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 CMerkleTx(CTransactionRef arg)
213 SetTx(std::move(arg));
214 Init();
217 /** Helper conversion operator to allow passing CMerkleTx where CTransaction is expected.
218 * TODO: adapt callers and remove this operator. */
219 operator const CTransaction&() const { return *tx; }
221 void Init()
223 hashBlock = uint256();
224 nIndex = -1;
227 void SetTx(CTransactionRef arg)
229 tx = std::move(arg);
232 ADD_SERIALIZE_METHODS;
234 template <typename Stream, typename Operation>
235 inline void SerializationOp(Stream& s, Operation ser_action) {
236 std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
237 READWRITE(tx);
238 READWRITE(hashBlock);
239 READWRITE(vMerkleBranch);
240 READWRITE(nIndex);
243 void SetMerkleBranch(const CBlockIndex* pIndex, int posInBlock);
246 * Return depth of transaction in blockchain:
247 * <0 : conflicts with a transaction this deep in the blockchain
248 * 0 : in memory pool, waiting to be included in a block
249 * >=1 : this many blocks deep in the main chain
251 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
252 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
253 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; }
254 int GetBlocksToMaturity() const;
255 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
256 bool AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state);
257 bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
258 bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
259 void setAbandoned() { hashBlock = ABANDON_HASH; }
261 const uint256& GetHash() const { return tx->GetHash(); }
262 bool IsCoinBase() const { return tx->IsCoinBase(); }
265 /**
266 * A transaction with a bunch of additional info that only the owner cares about.
267 * It includes any unrecorded transactions needed to link it back to the block chain.
269 class CWalletTx : public CMerkleTx
271 private:
272 const CWallet* pwallet;
274 public:
276 * Key/value map with information about the transaction.
278 * The following keys can be read and written through the map and are
279 * serialized in the wallet database:
281 * "comment", "to" - comment strings provided to sendtoaddress,
282 * sendfrom, sendmany wallet RPCs
283 * "replaces_txid" - txid (as HexStr) of transaction replaced by
284 * bumpfee on transaction created by bumpfee
285 * "replaced_by_txid" - txid (as HexStr) of transaction created by
286 * bumpfee on transaction replaced by bumpfee
287 * "from", "message" - obsolete fields that could be set in UI prior to
288 * 2011 (removed in commit 4d9b223)
290 * The following keys are serialized in the wallet database, but shouldn't
291 * be read or written through the map (they will be temporarily added and
292 * removed from the map during serialization):
294 * "fromaccount" - serialized strFromAccount value
295 * "n" - serialized nOrderPos value
296 * "timesmart" - serialized nTimeSmart value
297 * "spent" - serialized vfSpent value that existed prior to
298 * 2014 (removed in commit 93a18a3)
300 mapValue_t mapValue;
301 std::vector<std::pair<std::string, std::string> > vOrderForm;
302 unsigned int fTimeReceivedIsTxTime;
303 unsigned int nTimeReceived; //!< time received by this node
305 * Stable timestamp that never changes, and reflects the order a transaction
306 * was added to the wallet. Timestamp is based on the block time for a
307 * transaction added as part of a block, or else the time when the
308 * transaction was received if it wasn't part of a block, with the timestamp
309 * adjusted in both cases so timestamp order matches the order transactions
310 * were added to the wallet. More details can be found in
311 * CWallet::ComputeTimeSmart().
313 unsigned int nTimeSmart;
315 * From me flag is set to 1 for transactions that were created by the wallet
316 * on this bitcoin node, and set to 0 for transactions that were created
317 * externally and came in through the network or sendrawtransaction RPC.
319 char fFromMe;
320 std::string strFromAccount;
321 int64_t nOrderPos; //!< position in ordered transaction list
323 // memory only
324 mutable bool fDebitCached;
325 mutable bool fCreditCached;
326 mutable bool fImmatureCreditCached;
327 mutable bool fAvailableCreditCached;
328 mutable bool fWatchDebitCached;
329 mutable bool fWatchCreditCached;
330 mutable bool fImmatureWatchCreditCached;
331 mutable bool fAvailableWatchCreditCached;
332 mutable bool fChangeCached;
333 mutable CAmount nDebitCached;
334 mutable CAmount nCreditCached;
335 mutable CAmount nImmatureCreditCached;
336 mutable CAmount nAvailableCreditCached;
337 mutable CAmount nWatchDebitCached;
338 mutable CAmount nWatchCreditCached;
339 mutable CAmount nImmatureWatchCreditCached;
340 mutable CAmount nAvailableWatchCreditCached;
341 mutable CAmount nChangeCached;
343 CWalletTx()
345 Init(NULL);
348 CWalletTx(const CWallet* pwalletIn, CTransactionRef arg) : CMerkleTx(std::move(arg))
350 Init(pwalletIn);
353 void Init(const CWallet* pwalletIn)
355 pwallet = pwalletIn;
356 mapValue.clear();
357 vOrderForm.clear();
358 fTimeReceivedIsTxTime = false;
359 nTimeReceived = 0;
360 nTimeSmart = 0;
361 fFromMe = false;
362 strFromAccount.clear();
363 fDebitCached = false;
364 fCreditCached = false;
365 fImmatureCreditCached = false;
366 fAvailableCreditCached = false;
367 fWatchDebitCached = false;
368 fWatchCreditCached = false;
369 fImmatureWatchCreditCached = false;
370 fAvailableWatchCreditCached = false;
371 fChangeCached = false;
372 nDebitCached = 0;
373 nCreditCached = 0;
374 nImmatureCreditCached = 0;
375 nAvailableCreditCached = 0;
376 nWatchDebitCached = 0;
377 nWatchCreditCached = 0;
378 nAvailableWatchCreditCached = 0;
379 nImmatureWatchCreditCached = 0;
380 nChangeCached = 0;
381 nOrderPos = -1;
384 ADD_SERIALIZE_METHODS;
386 template <typename Stream, typename Operation>
387 inline void SerializationOp(Stream& s, Operation ser_action) {
388 if (ser_action.ForRead())
389 Init(NULL);
390 char fSpent = false;
392 if (!ser_action.ForRead())
394 mapValue["fromaccount"] = strFromAccount;
396 WriteOrderPos(nOrderPos, mapValue);
398 if (nTimeSmart)
399 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
402 READWRITE(*(CMerkleTx*)this);
403 std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
404 READWRITE(vUnused);
405 READWRITE(mapValue);
406 READWRITE(vOrderForm);
407 READWRITE(fTimeReceivedIsTxTime);
408 READWRITE(nTimeReceived);
409 READWRITE(fFromMe);
410 READWRITE(fSpent);
412 if (ser_action.ForRead())
414 strFromAccount = mapValue["fromaccount"];
416 ReadOrderPos(nOrderPos, mapValue);
418 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
421 mapValue.erase("fromaccount");
422 mapValue.erase("spent");
423 mapValue.erase("n");
424 mapValue.erase("timesmart");
427 //! make sure balances are recalculated
428 void MarkDirty()
430 fCreditCached = false;
431 fAvailableCreditCached = false;
432 fImmatureCreditCached = false;
433 fWatchDebitCached = false;
434 fWatchCreditCached = false;
435 fAvailableWatchCreditCached = false;
436 fImmatureWatchCreditCached = false;
437 fDebitCached = false;
438 fChangeCached = false;
441 void BindWallet(CWallet *pwalletIn)
443 pwallet = pwalletIn;
444 MarkDirty();
447 //! filter decides which addresses will count towards the debit
448 CAmount GetDebit(const isminefilter& filter) const;
449 CAmount GetCredit(const isminefilter& filter) const;
450 CAmount GetImmatureCredit(bool fUseCache=true) const;
451 CAmount GetAvailableCredit(bool fUseCache=true) const;
452 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
453 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
454 CAmount GetChange() const;
456 void GetAmounts(std::list<COutputEntry>& listReceived,
457 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
459 bool IsFromMe(const isminefilter& filter) const
461 return (GetDebit(filter) > 0);
464 // True if only scriptSigs are different
465 bool IsEquivalentTo(const CWalletTx& tx) const;
467 bool InMempool() const;
468 bool IsTrusted() const;
470 int64_t GetTxTime() const;
471 int GetRequestCount() const;
473 bool RelayWalletTransaction(CConnman* connman);
475 std::set<uint256> GetConflicts() const;
479 class CInputCoin {
480 public:
481 CInputCoin(const CWalletTx* walletTx, unsigned int i)
483 if (!walletTx)
484 throw std::invalid_argument("walletTx should not be null");
485 if (i >= walletTx->tx->vout.size())
486 throw std::out_of_range("The output index is out of range");
488 outpoint = COutPoint(walletTx->GetHash(), i);
489 txout = walletTx->tx->vout[i];
492 COutPoint outpoint;
493 CTxOut txout;
495 bool operator<(const CInputCoin& rhs) const {
496 return outpoint < rhs.outpoint;
499 bool operator!=(const CInputCoin& rhs) const {
500 return outpoint != rhs.outpoint;
503 bool operator==(const CInputCoin& rhs) const {
504 return outpoint == rhs.outpoint;
508 class COutput
510 public:
511 const CWalletTx *tx;
512 int i;
513 int nDepth;
515 /** Whether we have the private keys to spend this output */
516 bool fSpendable;
518 /** Whether we know how to spend this output, ignoring the lack of keys */
519 bool fSolvable;
522 * Whether this output is considered safe to spend. Unconfirmed transactions
523 * from outside keys and unconfirmed replacement transactions are considered
524 * unsafe and will not be used to fund new spending transactions.
526 bool fSafe;
528 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn)
530 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn;
533 std::string ToString() const;
539 /** Private key that includes an expiration date in case it never gets used. */
540 class CWalletKey
542 public:
543 CPrivKey vchPrivKey;
544 int64_t nTimeCreated;
545 int64_t nTimeExpires;
546 std::string strComment;
547 //! todo: add something to note what created it (user, getnewaddress, change)
548 //! maybe should have a map<string, string> property map
550 CWalletKey(int64_t nExpires=0);
552 ADD_SERIALIZE_METHODS;
554 template <typename Stream, typename Operation>
555 inline void SerializationOp(Stream& s, Operation ser_action) {
556 int nVersion = s.GetVersion();
557 if (!(s.GetType() & SER_GETHASH))
558 READWRITE(nVersion);
559 READWRITE(vchPrivKey);
560 READWRITE(nTimeCreated);
561 READWRITE(nTimeExpires);
562 READWRITE(LIMITED_STRING(strComment, 65536));
567 * Internal transfers.
568 * Database key is acentry<account><counter>.
570 class CAccountingEntry
572 public:
573 std::string strAccount;
574 CAmount nCreditDebit;
575 int64_t nTime;
576 std::string strOtherAccount;
577 std::string strComment;
578 mapValue_t mapValue;
579 int64_t nOrderPos; //!< position in ordered transaction list
580 uint64_t nEntryNo;
582 CAccountingEntry()
584 SetNull();
587 void SetNull()
589 nCreditDebit = 0;
590 nTime = 0;
591 strAccount.clear();
592 strOtherAccount.clear();
593 strComment.clear();
594 nOrderPos = -1;
595 nEntryNo = 0;
598 ADD_SERIALIZE_METHODS;
600 template <typename Stream, typename Operation>
601 inline void SerializationOp(Stream& s, Operation ser_action) {
602 int nVersion = s.GetVersion();
603 if (!(s.GetType() & SER_GETHASH))
604 READWRITE(nVersion);
605 //! Note: strAccount is serialized as part of the key, not here.
606 READWRITE(nCreditDebit);
607 READWRITE(nTime);
608 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
610 if (!ser_action.ForRead())
612 WriteOrderPos(nOrderPos, mapValue);
614 if (!(mapValue.empty() && _ssExtra.empty()))
616 CDataStream ss(s.GetType(), s.GetVersion());
617 ss.insert(ss.begin(), '\0');
618 ss << mapValue;
619 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
620 strComment.append(ss.str());
624 READWRITE(LIMITED_STRING(strComment, 65536));
626 size_t nSepPos = strComment.find("\0", 0, 1);
627 if (ser_action.ForRead())
629 mapValue.clear();
630 if (std::string::npos != nSepPos)
632 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
633 ss >> mapValue;
634 _ssExtra = std::vector<char>(ss.begin(), ss.end());
636 ReadOrderPos(nOrderPos, mapValue);
638 if (std::string::npos != nSepPos)
639 strComment.erase(nSepPos);
641 mapValue.erase("n");
644 private:
645 std::vector<char> _ssExtra;
649 /**
650 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
651 * and provides the ability to create new transactions.
653 class CWallet : public CCryptoKeyStore, public CValidationInterface
655 private:
656 static std::atomic<bool> fFlushScheduled;
657 std::atomic<bool> fAbortRescan;
658 std::atomic<bool> fScanningWallet;
661 * Select a set of coins such that nValueRet >= nTargetValue and at least
662 * all coins from coinControl are selected; Never select unconfirmed coins
663 * if they are not ours
665 bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL) const;
667 CWalletDB *pwalletdbEncryption;
669 //! the current wallet version: clients below this version are not able to load the wallet
670 int nWalletVersion;
672 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
673 int nWalletMaxVersion;
675 int64_t nNextResend;
676 int64_t nLastResend;
677 bool fBroadcastTransactions;
680 * Used to keep track of spent outpoints, and
681 * detect and report conflicts (double-spends or
682 * mutated transactions where the mutant gets mined).
684 typedef std::multimap<COutPoint, uint256> TxSpends;
685 TxSpends mapTxSpends;
686 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
687 void AddToSpends(const uint256& wtxid);
689 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
690 void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
692 void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
694 /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected.
695 * Should be called with pindexBlock and posInBlock if this is for a transaction that is included in a block. */
696 void SyncTransaction(const CTransactionRef& tx, const CBlockIndex *pindex = NULL, int posInBlock = 0);
698 /* the HD chain data model (external chain counters) */
699 CHDChain hdChain;
701 /* HD derive new child key (on internal or external chain) */
702 void DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal = false);
704 std::set<int64_t> setInternalKeyPool;
705 std::set<int64_t> setExternalKeyPool;
706 int64_t m_max_keypool_index;
708 int64_t nTimeFirstKey;
711 * Private version of AddWatchOnly method which does not accept a
712 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
713 * the watch key did not previously have a timestamp associated with it.
714 * Because this is an inherited virtual method, it is accessible despite
715 * being marked private, but it is marked private anyway to encourage use
716 * of the other AddWatchOnly which accepts a timestamp and sets
717 * nTimeFirstKey more intelligently for more efficient rescans.
719 bool AddWatchOnly(const CScript& dest) override;
721 std::unique_ptr<CWalletDBWrapper> dbw;
723 public:
725 * Main wallet lock.
726 * This lock protects all the fields added by CWallet.
728 mutable CCriticalSection cs_wallet;
730 /** Get database handle used by this wallet. Ideally this function would
731 * not be necessary.
733 CWalletDBWrapper& GetDBHandle()
735 return *dbw;
738 /** Get a name for this wallet for logging/debugging purposes.
740 std::string GetName() const
742 if (dbw) {
743 return dbw->GetName();
744 } else {
745 return "dummy";
749 void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
751 if (keypool.fInternal) {
752 setInternalKeyPool.insert(nIndex);
753 } else {
754 setExternalKeyPool.insert(nIndex);
756 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
758 // If no metadata exists yet, create a default with the pool key's
759 // creation time. Note that this may be overwritten by actually
760 // stored metadata for that key later, which is fine.
761 CKeyID keyid = keypool.vchPubKey.GetID();
762 if (mapKeyMetadata.count(keyid) == 0)
763 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
766 // Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
767 // key metadata.
768 std::map<CTxDestination, CKeyMetadata> mapKeyMetadata;
770 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
771 MasterKeyMap mapMasterKeys;
772 unsigned int nMasterKeyMaxID;
774 // Create wallet with dummy database handle
775 CWallet(): dbw(new CWalletDBWrapper())
777 SetNull();
780 // Create wallet with passed-in database handle
781 CWallet(std::unique_ptr<CWalletDBWrapper> dbw_in) : dbw(std::move(dbw_in))
783 SetNull();
786 ~CWallet()
788 delete pwalletdbEncryption;
789 pwalletdbEncryption = NULL;
792 void SetNull()
794 nWalletVersion = FEATURE_BASE;
795 nWalletMaxVersion = FEATURE_BASE;
796 nMasterKeyMaxID = 0;
797 pwalletdbEncryption = NULL;
798 nOrderPosNext = 0;
799 nAccountingEntryNumber = 0;
800 nNextResend = 0;
801 nLastResend = 0;
802 m_max_keypool_index = 0;
803 nTimeFirstKey = 0;
804 fBroadcastTransactions = false;
805 nRelockTime = 0;
806 fAbortRescan = false;
807 fScanningWallet = false;
810 std::map<uint256, CWalletTx> mapWallet;
811 std::list<CAccountingEntry> laccentries;
813 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
814 typedef std::multimap<int64_t, TxPair > TxItems;
815 TxItems wtxOrdered;
817 int64_t nOrderPosNext;
818 uint64_t nAccountingEntryNumber;
819 std::map<uint256, int> mapRequestCount;
821 std::map<CTxDestination, CAddressBookData> mapAddressBook;
823 CPubKey vchDefaultKey;
825 std::set<COutPoint> setLockedCoins;
827 const CWalletTx* GetWalletTx(const uint256& hash) const;
829 //! check whether we are allowed to upgrade (or already support) to the named feature
830 bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
833 * populate vCoins with vector of available COutputs.
835 void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlySafe=true, const CCoinControl *coinControl = NULL, 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;
838 * Return list of available coins and locked coins grouped by non-change output address.
840 std::map<CTxDestination, std::vector<COutput>> ListCoins() const;
843 * Find non-change parent output.
845 const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const;
848 * Shuffle and select coins until nTargetValue is reached while avoiding
849 * small change; This method is stochastic for some inputs and upon
850 * completion the coin set and corresponding actual target value is
851 * assembled
853 bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const;
855 bool IsSpent(const uint256& hash, unsigned int n) const;
857 bool IsLockedCoin(uint256 hash, unsigned int n) const;
858 void LockCoin(const COutPoint& output);
859 void UnlockCoin(const COutPoint& output);
860 void UnlockAllCoins();
861 void ListLockedCoins(std::vector<COutPoint>& vOutpts) const;
864 * Rescan abort properties
866 void AbortRescan() { fAbortRescan = true; }
867 bool IsAbortingRescan() { return fAbortRescan; }
868 bool IsScanning() { return fScanningWallet; }
871 * keystore implementation
872 * Generate a new key
874 CPubKey GenerateNewKey(CWalletDB& walletdb, bool internal = false);
875 //! Adds a key to the store, and saves it to disk.
876 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
877 bool AddKeyPubKeyWithDB(CWalletDB &walletdb,const CKey& key, const CPubKey &pubkey);
878 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
879 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
880 //! Load metadata (used by LoadWallet)
881 bool LoadKeyMetadata(const CTxDestination& pubKey, const CKeyMetadata &metadata);
883 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
884 void UpdateTimeFirstKey(int64_t nCreateTime);
886 //! Adds an encrypted key to the store, and saves it to disk.
887 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) override;
888 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
889 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
890 bool AddCScript(const CScript& redeemScript) override;
891 bool LoadCScript(const CScript& redeemScript);
893 //! Adds a destination data tuple to the store, and saves it to disk
894 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
895 //! Erases a destination data tuple in the store and on disk
896 bool EraseDestData(const CTxDestination &dest, const std::string &key);
897 //! Adds a destination data tuple to the store, without saving it to disk
898 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
899 //! Look up a destination data tuple in the store, return true if found false otherwise
900 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
901 //! Get all destination values matching a prefix.
902 std::vector<std::string> GetDestValues(const std::string& prefix) const;
904 //! Adds a watch-only address to the store, and saves it to disk.
905 bool AddWatchOnly(const CScript& dest, int64_t nCreateTime);
906 bool RemoveWatchOnly(const CScript &dest) override;
907 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
908 bool LoadWatchOnly(const CScript &dest);
910 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
911 int64_t nRelockTime;
913 bool Unlock(const SecureString& strWalletPassphrase);
914 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
915 bool EncryptWallet(const SecureString& strWalletPassphrase);
917 void GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const;
918 unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
920 /**
921 * Increment the next transaction order id
922 * @return next transaction order id
924 int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
925 DBErrors ReorderTransactions();
926 bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
927 bool GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew = false);
929 void MarkDirty();
930 bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
931 bool LoadToWallet(const CWalletTx& wtxIn);
932 void TransactionAddedToMempool(const CTransactionRef& tx) override;
933 void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) override;
934 void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override;
935 bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
936 int64_t RescanFromTime(int64_t startTime, bool update);
937 CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
938 void ReacceptWalletTransactions();
939 void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) override;
940 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
941 CAmount GetBalance() const;
942 CAmount GetUnconfirmedBalance() const;
943 CAmount GetImmatureBalance() const;
944 CAmount GetWatchOnlyBalance() const;
945 CAmount GetUnconfirmedWatchOnlyBalance() const;
946 CAmount GetImmatureWatchOnlyBalance() const;
947 CAmount GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const;
948 CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
951 * Insert additional inputs into the transaction by
952 * calling CreateTransaction();
954 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
955 bool SignTransaction(CMutableTransaction& tx);
958 * Create a new transaction paying the recipients with a set of coins
959 * selected by SelectCoins(); Also create the change output, when needed
960 * @note passing nChangePosInOut as -1 will result in setting a random position
962 bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
963 std::string& strFailReason, const CCoinControl& coin_control, bool sign = true);
964 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
966 void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
967 bool AddAccountingEntry(const CAccountingEntry&);
968 bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
969 template <typename ContainerType>
970 bool DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const;
972 static CFeeRate minTxFee;
973 static CFeeRate fallbackFee;
974 static CFeeRate m_discard_rate;
976 * Estimate the minimum fee considering user set parameters
977 * and the required fee
979 static CAmount GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc);
981 * Return the minimum required fee taking into account the
982 * floating relay fee and user set minimum transaction fee
984 static CAmount GetRequiredFee(unsigned int nTxBytes);
986 bool NewKeyPool();
987 size_t KeypoolCountExternalKeys();
988 bool TopUpKeyPool(unsigned int kpSize = 0);
989 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
990 void KeepKey(int64_t nIndex);
991 void ReturnKey(int64_t nIndex, bool fInternal);
992 bool GetKeyFromPool(CPubKey &key, bool internal = false);
993 int64_t GetOldestKeyPoolTime();
994 void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
996 std::set< std::set<CTxDestination> > GetAddressGroupings();
997 std::map<CTxDestination, CAmount> GetAddressBalances();
999 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
1001 isminetype IsMine(const CTxIn& txin) const;
1003 * Returns amount of debit if the input matches the
1004 * filter, otherwise returns 0
1006 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1007 isminetype IsMine(const CTxOut& txout) const;
1008 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1009 bool IsChange(const CTxOut& txout) const;
1010 CAmount GetChange(const CTxOut& txout) const;
1011 bool IsMine(const CTransaction& tx) const;
1012 /** should probably be renamed to IsRelevantToMe */
1013 bool IsFromMe(const CTransaction& tx) const;
1014 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1015 /** Returns whether all of the inputs match the filter */
1016 bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1017 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1018 CAmount GetChange(const CTransaction& tx) const;
1019 void SetBestChain(const CBlockLocator& loc) override;
1021 DBErrors LoadWallet(bool& fFirstRunRet);
1022 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1023 DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut);
1025 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1027 bool DelAddressBook(const CTxDestination& address);
1029 const std::string& GetAccountName(const CScript& scriptPubKey) const;
1031 void Inventory(const uint256 &hash) override
1034 LOCK(cs_wallet);
1035 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
1036 if (mi != mapRequestCount.end())
1037 (*mi).second++;
1041 void GetScriptForMining(std::shared_ptr<CReserveScript> &script);
1043 unsigned int GetKeyPoolSize()
1045 AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool
1046 return setInternalKeyPool.size() + setExternalKeyPool.size();
1049 bool SetDefaultKey(const CPubKey &vchPubKey);
1051 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1052 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
1054 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1055 bool SetMaxVersion(int nVersion);
1057 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1058 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1060 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1061 std::set<uint256> GetConflicts(const uint256& txid) const;
1063 //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
1064 bool HasWalletSpend(const uint256& txid) const;
1066 //! Flush wallet (bitdb flush)
1067 void Flush(bool shutdown=false);
1069 //! Responsible for reading and validating the -wallet arguments and verifying the wallet database.
1070 // This function will perform salvage on the wallet if requested, as long as only one wallet is
1071 // being loaded (CWallet::ParameterInteraction forbids -salvagewallet, -zapwallettxes or -upgradewallet with multiwallet).
1072 static bool Verify();
1074 /**
1075 * Address book entry changed.
1076 * @note called with lock cs_wallet held.
1078 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1079 &address, const std::string &label, bool isMine,
1080 const std::string &purpose,
1081 ChangeType status)> NotifyAddressBookChanged;
1083 /**
1084 * Wallet transaction added, removed or updated.
1085 * @note called with lock cs_wallet held.
1087 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1088 ChangeType status)> NotifyTransactionChanged;
1090 /** Show progress e.g. for rescan */
1091 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1093 /** Watch-only address added */
1094 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1096 /** Inquire whether this wallet broadcasts transactions. */
1097 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1098 /** Set whether this wallet broadcasts transactions. */
1099 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1101 /** Return whether transaction can be abandoned */
1102 bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1104 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1105 bool AbandonTransaction(const uint256& hashTx);
1107 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1108 bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1110 /* Returns the wallets help message */
1111 static std::string GetWalletHelpString(bool showDebug);
1113 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1114 static CWallet* CreateWalletFromFile(const std::string walletFile);
1115 static bool InitLoadWallet();
1118 * Wallet post-init setup
1119 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1121 void postInitProcess(CScheduler& scheduler);
1123 /* Wallets parameter interaction */
1124 static bool ParameterInteraction();
1126 bool BackupWallet(const std::string& strDest);
1128 /* Set the HD chain model (chain child index counters) */
1129 bool SetHDChain(const CHDChain& chain, bool memonly);
1130 const CHDChain& GetHDChain() const { return hdChain; }
1132 /* Returns true if HD is enabled */
1133 bool IsHDEnabled() const;
1135 /* Generates a new HD master key (will not be activated) */
1136 CPubKey GenerateNewHDMasterKey();
1138 /* Set the current HD master key (will reset the chain child index counters)
1139 Sets the master key's version based on the current wallet version (so the
1140 caller must ensure the current wallet version is correct before calling
1141 this function). */
1142 bool SetHDMasterKey(const CPubKey& key);
1145 /** A key allocated from the key pool. */
1146 class CReserveKey : public CReserveScript
1148 protected:
1149 CWallet* pwallet;
1150 int64_t nIndex;
1151 CPubKey vchPubKey;
1152 bool fInternal;
1153 public:
1154 CReserveKey(CWallet* pwalletIn)
1156 nIndex = -1;
1157 pwallet = pwalletIn;
1158 fInternal = false;
1161 CReserveKey() = default;
1162 CReserveKey(const CReserveKey&) = delete;
1163 CReserveKey& operator=(const CReserveKey&) = delete;
1165 ~CReserveKey()
1167 ReturnKey();
1170 void ReturnKey();
1171 bool GetReservedKey(CPubKey &pubkey, bool internal = false);
1172 void KeepKey();
1173 void KeepScript() override { KeepKey(); }
1177 /**
1178 * Account information.
1179 * Stored in wallet with key "acc"+string account name.
1181 class CAccount
1183 public:
1184 CPubKey vchPubKey;
1186 CAccount()
1188 SetNull();
1191 void SetNull()
1193 vchPubKey = CPubKey();
1196 ADD_SERIALIZE_METHODS;
1198 template <typename Stream, typename Operation>
1199 inline void SerializationOp(Stream& s, Operation ser_action) {
1200 int nVersion = s.GetVersion();
1201 if (!(s.GetType() & SER_GETHASH))
1202 READWRITE(nVersion);
1203 READWRITE(vchPubKey);
1207 // Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
1208 // ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
1209 // so that each entry corresponds to each vIn, in order.
1210 template <typename ContainerType>
1211 bool CWallet::DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const
1213 // Fill in dummy signatures for fee calculation.
1214 int nIn = 0;
1215 for (const auto& coin : coins)
1217 const CScript& scriptPubKey = coin.txout.scriptPubKey;
1218 SignatureData sigdata;
1220 if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata))
1222 return false;
1223 } else {
1224 UpdateTransaction(txNew, nIn, sigdata);
1227 nIn++;
1229 return true;
1232 #endif // BITCOIN_WALLET_WALLET_H