Merge #11250: Bump wallet version to 159900 and remove the `usehd` option
[bitcoinplatinum.git] / src / wallet / wallet.h
blob542e9bd5c14a319756b126bd49e63f60b97a160b
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 getwalletinfo'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_NO_DEFAULT_KEY = 159900, // Wallet without a default key written
101 FEATURE_LATEST = FEATURE_COMPRPUBKEY // HD is optional, use FEATURE_COMPRPUBKEY as latest version
105 /** A key pool entry */
106 class CKeyPool
108 public:
109 int64_t nTime;
110 CPubKey vchPubKey;
111 bool fInternal; // for change outputs
113 CKeyPool();
114 CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn);
116 ADD_SERIALIZE_METHODS;
118 template <typename Stream, typename Operation>
119 inline void SerializationOp(Stream& s, Operation ser_action) {
120 int nVersion = s.GetVersion();
121 if (!(s.GetType() & SER_GETHASH))
122 READWRITE(nVersion);
123 READWRITE(nTime);
124 READWRITE(vchPubKey);
125 if (ser_action.ForRead()) {
126 try {
127 READWRITE(fInternal);
129 catch (std::ios_base::failure&) {
130 /* flag as external address if we can't read the internal boolean
131 (this will be the case for any wallet before the HD chain split version) */
132 fInternal = false;
135 else {
136 READWRITE(fInternal);
141 /** Address book data */
142 class CAddressBookData
144 public:
145 std::string name;
146 std::string purpose;
148 CAddressBookData() : purpose("unknown") {}
150 typedef std::map<std::string, std::string> StringMap;
151 StringMap destdata;
154 struct CRecipient
156 CScript scriptPubKey;
157 CAmount nAmount;
158 bool fSubtractFeeFromAmount;
161 typedef std::map<std::string, std::string> mapValue_t;
164 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
166 if (!mapValue.count("n"))
168 nOrderPos = -1; // TODO: calculate elsewhere
169 return;
171 nOrderPos = atoi64(mapValue["n"].c_str());
175 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
177 if (nOrderPos == -1)
178 return;
179 mapValue["n"] = i64tostr(nOrderPos);
182 struct COutputEntry
184 CTxDestination destination;
185 CAmount amount;
186 int vout;
189 /** A transaction with a merkle branch linking it to the block chain. */
190 class CMerkleTx
192 private:
193 /** Constant used in hashBlock to indicate tx has been abandoned */
194 static const uint256 ABANDON_HASH;
196 public:
197 CTransactionRef tx;
198 uint256 hashBlock;
200 /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
201 * block in the chain we know this or any in-wallet dependency conflicts
202 * with. Older clients interpret nIndex == -1 as unconfirmed for backward
203 * compatibility.
205 int nIndex;
207 CMerkleTx()
209 SetTx(MakeTransactionRef());
210 Init();
213 explicit CMerkleTx(CTransactionRef arg)
215 SetTx(std::move(arg));
216 Init();
219 /** Helper conversion operator to allow passing CMerkleTx where CTransaction is expected.
220 * TODO: adapt callers and remove this operator. */
221 operator const CTransaction&() const { return *tx; }
223 void Init()
225 hashBlock = uint256();
226 nIndex = -1;
229 void SetTx(CTransactionRef arg)
231 tx = std::move(arg);
234 ADD_SERIALIZE_METHODS;
236 template <typename Stream, typename Operation>
237 inline void SerializationOp(Stream& s, Operation ser_action) {
238 std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
239 READWRITE(tx);
240 READWRITE(hashBlock);
241 READWRITE(vMerkleBranch);
242 READWRITE(nIndex);
245 void SetMerkleBranch(const CBlockIndex* pIndex, int posInBlock);
248 * Return depth of transaction in blockchain:
249 * <0 : conflicts with a transaction this deep in the blockchain
250 * 0 : in memory pool, waiting to be included in a block
251 * >=1 : this many blocks deep in the main chain
253 int GetDepthInMainChain(const CBlockIndex* &pindexRet) const;
254 int GetDepthInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
255 bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; }
256 int GetBlocksToMaturity() const;
257 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
258 bool AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state);
259 bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
260 bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
261 void setAbandoned() { hashBlock = ABANDON_HASH; }
263 const uint256& GetHash() const { return tx->GetHash(); }
264 bool IsCoinBase() const { return tx->IsCoinBase(); }
267 /**
268 * A transaction with a bunch of additional info that only the owner cares about.
269 * It includes any unrecorded transactions needed to link it back to the block chain.
271 class CWalletTx : public CMerkleTx
273 private:
274 const CWallet* pwallet;
276 public:
278 * Key/value map with information about the transaction.
280 * The following keys can be read and written through the map and are
281 * serialized in the wallet database:
283 * "comment", "to" - comment strings provided to sendtoaddress,
284 * sendfrom, sendmany wallet RPCs
285 * "replaces_txid" - txid (as HexStr) of transaction replaced by
286 * bumpfee on transaction created by bumpfee
287 * "replaced_by_txid" - txid (as HexStr) of transaction created by
288 * bumpfee on transaction replaced by bumpfee
289 * "from", "message" - obsolete fields that could be set in UI prior to
290 * 2011 (removed in commit 4d9b223)
292 * The following keys are serialized in the wallet database, but shouldn't
293 * be read or written through the map (they will be temporarily added and
294 * removed from the map during serialization):
296 * "fromaccount" - serialized strFromAccount value
297 * "n" - serialized nOrderPos value
298 * "timesmart" - serialized nTimeSmart value
299 * "spent" - serialized vfSpent value that existed prior to
300 * 2014 (removed in commit 93a18a3)
302 mapValue_t mapValue;
303 std::vector<std::pair<std::string, std::string> > vOrderForm;
304 unsigned int fTimeReceivedIsTxTime;
305 unsigned int nTimeReceived; //!< time received by this node
307 * Stable timestamp that never changes, and reflects the order a transaction
308 * was added to the wallet. Timestamp is based on the block time for a
309 * transaction added as part of a block, or else the time when the
310 * transaction was received if it wasn't part of a block, with the timestamp
311 * adjusted in both cases so timestamp order matches the order transactions
312 * were added to the wallet. More details can be found in
313 * CWallet::ComputeTimeSmart().
315 unsigned int nTimeSmart;
317 * From me flag is set to 1 for transactions that were created by the wallet
318 * on this bitcoin node, and set to 0 for transactions that were created
319 * externally and came in through the network or sendrawtransaction RPC.
321 char fFromMe;
322 std::string strFromAccount;
323 int64_t nOrderPos; //!< position in ordered transaction list
325 // memory only
326 mutable bool fDebitCached;
327 mutable bool fCreditCached;
328 mutable bool fImmatureCreditCached;
329 mutable bool fAvailableCreditCached;
330 mutable bool fWatchDebitCached;
331 mutable bool fWatchCreditCached;
332 mutable bool fImmatureWatchCreditCached;
333 mutable bool fAvailableWatchCreditCached;
334 mutable bool fChangeCached;
335 mutable CAmount nDebitCached;
336 mutable CAmount nCreditCached;
337 mutable CAmount nImmatureCreditCached;
338 mutable CAmount nAvailableCreditCached;
339 mutable CAmount nWatchDebitCached;
340 mutable CAmount nWatchCreditCached;
341 mutable CAmount nImmatureWatchCreditCached;
342 mutable CAmount nAvailableWatchCreditCached;
343 mutable CAmount nChangeCached;
345 CWalletTx()
347 Init(nullptr);
350 CWalletTx(const CWallet* pwalletIn, CTransactionRef arg) : CMerkleTx(std::move(arg))
352 Init(pwalletIn);
355 void Init(const CWallet* pwalletIn)
357 pwallet = pwalletIn;
358 mapValue.clear();
359 vOrderForm.clear();
360 fTimeReceivedIsTxTime = false;
361 nTimeReceived = 0;
362 nTimeSmart = 0;
363 fFromMe = false;
364 strFromAccount.clear();
365 fDebitCached = false;
366 fCreditCached = false;
367 fImmatureCreditCached = false;
368 fAvailableCreditCached = false;
369 fWatchDebitCached = false;
370 fWatchCreditCached = false;
371 fImmatureWatchCreditCached = false;
372 fAvailableWatchCreditCached = false;
373 fChangeCached = false;
374 nDebitCached = 0;
375 nCreditCached = 0;
376 nImmatureCreditCached = 0;
377 nAvailableCreditCached = 0;
378 nWatchDebitCached = 0;
379 nWatchCreditCached = 0;
380 nAvailableWatchCreditCached = 0;
381 nImmatureWatchCreditCached = 0;
382 nChangeCached = 0;
383 nOrderPos = -1;
386 ADD_SERIALIZE_METHODS;
388 template <typename Stream, typename Operation>
389 inline void SerializationOp(Stream& s, Operation ser_action) {
390 if (ser_action.ForRead())
391 Init(nullptr);
392 char fSpent = false;
394 if (!ser_action.ForRead())
396 mapValue["fromaccount"] = strFromAccount;
398 WriteOrderPos(nOrderPos, mapValue);
400 if (nTimeSmart)
401 mapValue["timesmart"] = strprintf("%u", nTimeSmart);
404 READWRITE(*(CMerkleTx*)this);
405 std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
406 READWRITE(vUnused);
407 READWRITE(mapValue);
408 READWRITE(vOrderForm);
409 READWRITE(fTimeReceivedIsTxTime);
410 READWRITE(nTimeReceived);
411 READWRITE(fFromMe);
412 READWRITE(fSpent);
414 if (ser_action.ForRead())
416 strFromAccount = mapValue["fromaccount"];
418 ReadOrderPos(nOrderPos, mapValue);
420 nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
423 mapValue.erase("fromaccount");
424 mapValue.erase("spent");
425 mapValue.erase("n");
426 mapValue.erase("timesmart");
429 //! make sure balances are recalculated
430 void MarkDirty()
432 fCreditCached = false;
433 fAvailableCreditCached = false;
434 fImmatureCreditCached = false;
435 fWatchDebitCached = false;
436 fWatchCreditCached = false;
437 fAvailableWatchCreditCached = false;
438 fImmatureWatchCreditCached = false;
439 fDebitCached = false;
440 fChangeCached = false;
443 void BindWallet(CWallet *pwalletIn)
445 pwallet = pwalletIn;
446 MarkDirty();
449 //! filter decides which addresses will count towards the debit
450 CAmount GetDebit(const isminefilter& filter) const;
451 CAmount GetCredit(const isminefilter& filter) const;
452 CAmount GetImmatureCredit(bool fUseCache=true) const;
453 CAmount GetAvailableCredit(bool fUseCache=true) const;
454 CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
455 CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
456 CAmount GetChange() const;
458 void GetAmounts(std::list<COutputEntry>& listReceived,
459 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
461 bool IsFromMe(const isminefilter& filter) const
463 return (GetDebit(filter) > 0);
466 // True if only scriptSigs are different
467 bool IsEquivalentTo(const CWalletTx& tx) const;
469 bool InMempool() const;
470 bool IsTrusted() const;
472 int64_t GetTxTime() const;
473 int GetRequestCount() const;
475 // RelayWalletTransaction may only be called if fBroadcastTransactions!
476 bool RelayWalletTransaction(CConnman* connman);
478 std::set<uint256> GetConflicts() const;
482 class CInputCoin {
483 public:
484 CInputCoin(const CWalletTx* walletTx, unsigned int i)
486 if (!walletTx)
487 throw std::invalid_argument("walletTx should not be null");
488 if (i >= walletTx->tx->vout.size())
489 throw std::out_of_range("The output index is out of range");
491 outpoint = COutPoint(walletTx->GetHash(), i);
492 txout = walletTx->tx->vout[i];
495 COutPoint outpoint;
496 CTxOut txout;
498 bool operator<(const CInputCoin& rhs) const {
499 return outpoint < rhs.outpoint;
502 bool operator!=(const CInputCoin& rhs) const {
503 return outpoint != rhs.outpoint;
506 bool operator==(const CInputCoin& rhs) const {
507 return outpoint == rhs.outpoint;
511 class COutput
513 public:
514 const CWalletTx *tx;
515 int i;
516 int nDepth;
518 /** Whether we have the private keys to spend this output */
519 bool fSpendable;
521 /** Whether we know how to spend this output, ignoring the lack of keys */
522 bool fSolvable;
525 * Whether this output is considered safe to spend. Unconfirmed transactions
526 * from outside keys and unconfirmed replacement transactions are considered
527 * unsafe and will not be used to fund new spending transactions.
529 bool fSafe;
531 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn)
533 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn;
536 std::string ToString() const;
542 /** Private key that includes an expiration date in case it never gets used. */
543 class CWalletKey
545 public:
546 CPrivKey vchPrivKey;
547 int64_t nTimeCreated;
548 int64_t nTimeExpires;
549 std::string strComment;
550 //! todo: add something to note what created it (user, getnewaddress, change)
551 //! maybe should have a map<string, string> property map
553 explicit CWalletKey(int64_t nExpires=0);
555 ADD_SERIALIZE_METHODS;
557 template <typename Stream, typename Operation>
558 inline void SerializationOp(Stream& s, Operation ser_action) {
559 int nVersion = s.GetVersion();
560 if (!(s.GetType() & SER_GETHASH))
561 READWRITE(nVersion);
562 READWRITE(vchPrivKey);
563 READWRITE(nTimeCreated);
564 READWRITE(nTimeExpires);
565 READWRITE(LIMITED_STRING(strComment, 65536));
570 * Internal transfers.
571 * Database key is acentry<account><counter>.
573 class CAccountingEntry
575 public:
576 std::string strAccount;
577 CAmount nCreditDebit;
578 int64_t nTime;
579 std::string strOtherAccount;
580 std::string strComment;
581 mapValue_t mapValue;
582 int64_t nOrderPos; //!< position in ordered transaction list
583 uint64_t nEntryNo;
585 CAccountingEntry()
587 SetNull();
590 void SetNull()
592 nCreditDebit = 0;
593 nTime = 0;
594 strAccount.clear();
595 strOtherAccount.clear();
596 strComment.clear();
597 nOrderPos = -1;
598 nEntryNo = 0;
601 ADD_SERIALIZE_METHODS;
603 template <typename Stream, typename Operation>
604 inline void SerializationOp(Stream& s, Operation ser_action) {
605 int nVersion = s.GetVersion();
606 if (!(s.GetType() & SER_GETHASH))
607 READWRITE(nVersion);
608 //! Note: strAccount is serialized as part of the key, not here.
609 READWRITE(nCreditDebit);
610 READWRITE(nTime);
611 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
613 if (!ser_action.ForRead())
615 WriteOrderPos(nOrderPos, mapValue);
617 if (!(mapValue.empty() && _ssExtra.empty()))
619 CDataStream ss(s.GetType(), s.GetVersion());
620 ss.insert(ss.begin(), '\0');
621 ss << mapValue;
622 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
623 strComment.append(ss.str());
627 READWRITE(LIMITED_STRING(strComment, 65536));
629 size_t nSepPos = strComment.find("\0", 0, 1);
630 if (ser_action.ForRead())
632 mapValue.clear();
633 if (std::string::npos != nSepPos)
635 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
636 ss >> mapValue;
637 _ssExtra = std::vector<char>(ss.begin(), ss.end());
639 ReadOrderPos(nOrderPos, mapValue);
641 if (std::string::npos != nSepPos)
642 strComment.erase(nSepPos);
644 mapValue.erase("n");
647 private:
648 std::vector<char> _ssExtra;
652 /**
653 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
654 * and provides the ability to create new transactions.
656 class CWallet final : public CCryptoKeyStore, public CValidationInterface
658 private:
659 static std::atomic<bool> fFlushScheduled;
660 std::atomic<bool> fAbortRescan;
661 std::atomic<bool> fScanningWallet;
664 * Select a set of coins such that nValueRet >= nTargetValue and at least
665 * all coins from coinControl are selected; Never select unconfirmed coins
666 * if they are not ours
668 bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = nullptr) const;
670 CWalletDB *pwalletdbEncryption;
672 //! the current wallet version: clients below this version are not able to load the wallet
673 int nWalletVersion;
675 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
676 int nWalletMaxVersion;
678 int64_t nNextResend;
679 int64_t nLastResend;
680 bool fBroadcastTransactions;
683 * Used to keep track of spent outpoints, and
684 * detect and report conflicts (double-spends or
685 * mutated transactions where the mutant gets mined).
687 typedef std::multimap<COutPoint, uint256> TxSpends;
688 TxSpends mapTxSpends;
689 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
690 void AddToSpends(const uint256& wtxid);
692 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
693 void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
695 void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
697 /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected.
698 * Should be called with pindexBlock and posInBlock if this is for a transaction that is included in a block. */
699 void SyncTransaction(const CTransactionRef& tx, const CBlockIndex *pindex = nullptr, int posInBlock = 0);
701 /* the HD chain data model (external chain counters) */
702 CHDChain hdChain;
704 /* HD derive new child key (on internal or external chain) */
705 void DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal = false);
707 std::set<int64_t> setInternalKeyPool;
708 std::set<int64_t> setExternalKeyPool;
709 int64_t m_max_keypool_index;
710 std::map<CKeyID, int64_t> m_pool_key_to_index;
712 int64_t nTimeFirstKey;
715 * Private version of AddWatchOnly method which does not accept a
716 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
717 * the watch key did not previously have a timestamp associated with it.
718 * Because this is an inherited virtual method, it is accessible despite
719 * being marked private, but it is marked private anyway to encourage use
720 * of the other AddWatchOnly which accepts a timestamp and sets
721 * nTimeFirstKey more intelligently for more efficient rescans.
723 bool AddWatchOnly(const CScript& dest) override;
725 std::unique_ptr<CWalletDBWrapper> dbw;
727 public:
729 * Main wallet lock.
730 * This lock protects all the fields added by CWallet.
732 mutable CCriticalSection cs_wallet;
734 /** Get database handle used by this wallet. Ideally this function would
735 * not be necessary.
737 CWalletDBWrapper& GetDBHandle()
739 return *dbw;
742 /** Get a name for this wallet for logging/debugging purposes.
744 std::string GetName() const
746 if (dbw) {
747 return dbw->GetName();
748 } else {
749 return "dummy";
753 void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool);
755 // Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
756 // key metadata.
757 std::map<CTxDestination, CKeyMetadata> mapKeyMetadata;
759 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
760 MasterKeyMap mapMasterKeys;
761 unsigned int nMasterKeyMaxID;
763 // Create wallet with dummy database handle
764 CWallet(): dbw(new CWalletDBWrapper())
766 SetNull();
769 // Create wallet with passed-in database handle
770 explicit CWallet(std::unique_ptr<CWalletDBWrapper> dbw_in) : dbw(std::move(dbw_in))
772 SetNull();
775 ~CWallet()
777 delete pwalletdbEncryption;
778 pwalletdbEncryption = nullptr;
781 void SetNull()
783 nWalletVersion = FEATURE_BASE;
784 nWalletMaxVersion = FEATURE_BASE;
785 nMasterKeyMaxID = 0;
786 pwalletdbEncryption = nullptr;
787 nOrderPosNext = 0;
788 nAccountingEntryNumber = 0;
789 nNextResend = 0;
790 nLastResend = 0;
791 m_max_keypool_index = 0;
792 nTimeFirstKey = 0;
793 fBroadcastTransactions = false;
794 nRelockTime = 0;
795 fAbortRescan = false;
796 fScanningWallet = false;
799 std::map<uint256, CWalletTx> mapWallet;
800 std::list<CAccountingEntry> laccentries;
802 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
803 typedef std::multimap<int64_t, TxPair > TxItems;
804 TxItems wtxOrdered;
806 int64_t nOrderPosNext;
807 uint64_t nAccountingEntryNumber;
808 std::map<uint256, int> mapRequestCount;
810 std::map<CTxDestination, CAddressBookData> mapAddressBook;
812 std::set<COutPoint> setLockedCoins;
814 const CWalletTx* GetWalletTx(const uint256& hash) const;
816 //! check whether we are allowed to upgrade (or already support) to the named feature
817 bool CanSupportFeature(enum WalletFeature wf) const { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
820 * populate vCoins with vector of available COutputs.
822 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;
825 * Return list of available coins and locked coins grouped by non-change output address.
827 std::map<CTxDestination, std::vector<COutput>> ListCoins() const;
830 * Find non-change parent output.
832 const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const;
835 * Shuffle and select coins until nTargetValue is reached while avoiding
836 * small change; This method is stochastic for some inputs and upon
837 * completion the coin set and corresponding actual target value is
838 * assembled
840 bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const;
842 bool IsSpent(const uint256& hash, unsigned int n) const;
844 bool IsLockedCoin(uint256 hash, unsigned int n) const;
845 void LockCoin(const COutPoint& output);
846 void UnlockCoin(const COutPoint& output);
847 void UnlockAllCoins();
848 void ListLockedCoins(std::vector<COutPoint>& vOutpts) const;
851 * Rescan abort properties
853 void AbortRescan() { fAbortRescan = true; }
854 bool IsAbortingRescan() { return fAbortRescan; }
855 bool IsScanning() { return fScanningWallet; }
858 * keystore implementation
859 * Generate a new key
861 CPubKey GenerateNewKey(CWalletDB& walletdb, bool internal = false);
862 //! Adds a key to the store, and saves it to disk.
863 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
864 bool AddKeyPubKeyWithDB(CWalletDB &walletdb,const CKey& key, const CPubKey &pubkey);
865 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
866 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
867 //! Load metadata (used by LoadWallet)
868 bool LoadKeyMetadata(const CTxDestination& pubKey, const CKeyMetadata &metadata);
870 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
871 void UpdateTimeFirstKey(int64_t nCreateTime);
873 //! Adds an encrypted key to the store, and saves it to disk.
874 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) override;
875 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
876 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
877 bool AddCScript(const CScript& redeemScript) override;
878 bool LoadCScript(const CScript& redeemScript);
880 //! Adds a destination data tuple to the store, and saves it to disk
881 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
882 //! Erases a destination data tuple in the store and on disk
883 bool EraseDestData(const CTxDestination &dest, const std::string &key);
884 //! Adds a destination data tuple to the store, without saving it to disk
885 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
886 //! Look up a destination data tuple in the store, return true if found false otherwise
887 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
888 //! Get all destination values matching a prefix.
889 std::vector<std::string> GetDestValues(const std::string& prefix) const;
891 //! Adds a watch-only address to the store, and saves it to disk.
892 bool AddWatchOnly(const CScript& dest, int64_t nCreateTime);
893 bool RemoveWatchOnly(const CScript &dest) override;
894 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
895 bool LoadWatchOnly(const CScript &dest);
897 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
898 int64_t nRelockTime;
900 bool Unlock(const SecureString& strWalletPassphrase);
901 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
902 bool EncryptWallet(const SecureString& strWalletPassphrase);
904 void GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const;
905 unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
907 /**
908 * Increment the next transaction order id
909 * @return next transaction order id
911 int64_t IncOrderPosNext(CWalletDB *pwalletdb = nullptr);
912 DBErrors ReorderTransactions();
913 bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
914 bool GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew = false);
916 void MarkDirty();
917 bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
918 bool LoadToWallet(const CWalletTx& wtxIn);
919 void TransactionAddedToMempool(const CTransactionRef& tx) override;
920 void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) override;
921 void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override;
922 bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
923 int64_t RescanFromTime(int64_t startTime, bool update);
924 CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
925 void ReacceptWalletTransactions();
926 void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) override;
927 // ResendWalletTransactionsBefore may only be called if fBroadcastTransactions!
928 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
929 CAmount GetBalance() const;
930 CAmount GetUnconfirmedBalance() const;
931 CAmount GetImmatureBalance() const;
932 CAmount GetWatchOnlyBalance() const;
933 CAmount GetUnconfirmedWatchOnlyBalance() const;
934 CAmount GetImmatureWatchOnlyBalance() const;
935 CAmount GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const;
936 CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
939 * Insert additional inputs into the transaction by
940 * calling CreateTransaction();
942 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
943 bool SignTransaction(CMutableTransaction& tx);
946 * Create a new transaction paying the recipients with a set of coins
947 * selected by SelectCoins(); Also create the change output, when needed
948 * @note passing nChangePosInOut as -1 will result in setting a random position
950 bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
951 std::string& strFailReason, const CCoinControl& coin_control, bool sign = true);
952 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
954 void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
955 bool AddAccountingEntry(const CAccountingEntry&);
956 bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
957 template <typename ContainerType>
958 bool DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const;
960 static CFeeRate minTxFee;
961 static CFeeRate fallbackFee;
962 static CFeeRate m_discard_rate;
964 bool NewKeyPool();
965 size_t KeypoolCountExternalKeys();
966 bool TopUpKeyPool(unsigned int kpSize = 0);
967 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
968 void KeepKey(int64_t nIndex);
969 void ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey);
970 bool GetKeyFromPool(CPubKey &key, bool internal = false);
971 int64_t GetOldestKeyPoolTime();
973 * Marks all keys in the keypool up to and including reserve_key as used.
975 void MarkReserveKeysAsUsed(int64_t keypool_id);
976 const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }
978 std::set< std::set<CTxDestination> > GetAddressGroupings();
979 std::map<CTxDestination, CAmount> GetAddressBalances();
981 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
983 isminetype IsMine(const CTxIn& txin) const;
985 * Returns amount of debit if the input matches the
986 * filter, otherwise returns 0
988 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
989 isminetype IsMine(const CTxOut& txout) const;
990 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
991 bool IsChange(const CTxOut& txout) const;
992 CAmount GetChange(const CTxOut& txout) const;
993 bool IsMine(const CTransaction& tx) const;
994 /** should probably be renamed to IsRelevantToMe */
995 bool IsFromMe(const CTransaction& tx) const;
996 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
997 /** Returns whether all of the inputs match the filter */
998 bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
999 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1000 CAmount GetChange(const CTransaction& tx) const;
1001 void SetBestChain(const CBlockLocator& loc) override;
1003 DBErrors LoadWallet(bool& fFirstRunRet);
1004 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1005 DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut);
1007 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1009 bool DelAddressBook(const CTxDestination& address);
1011 const std::string& GetAccountName(const CScript& scriptPubKey) const;
1013 void Inventory(const uint256 &hash) override
1016 LOCK(cs_wallet);
1017 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
1018 if (mi != mapRequestCount.end())
1019 (*mi).second++;
1023 void GetScriptForMining(std::shared_ptr<CReserveScript> &script);
1025 unsigned int GetKeyPoolSize()
1027 AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool
1028 return setInternalKeyPool.size() + setExternalKeyPool.size();
1031 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1032 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = nullptr, bool fExplicit = false);
1034 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1035 bool SetMaxVersion(int nVersion);
1037 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1038 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1040 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1041 std::set<uint256> GetConflicts(const uint256& txid) const;
1043 //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
1044 bool HasWalletSpend(const uint256& txid) const;
1046 //! Flush wallet (bitdb flush)
1047 void Flush(bool shutdown=false);
1049 /**
1050 * Address book entry changed.
1051 * @note called with lock cs_wallet held.
1053 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1054 &address, const std::string &label, bool isMine,
1055 const std::string &purpose,
1056 ChangeType status)> NotifyAddressBookChanged;
1058 /**
1059 * Wallet transaction added, removed or updated.
1060 * @note called with lock cs_wallet held.
1062 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1063 ChangeType status)> NotifyTransactionChanged;
1065 /** Show progress e.g. for rescan */
1066 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1068 /** Watch-only address added */
1069 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1071 /** Inquire whether this wallet broadcasts transactions. */
1072 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1073 /** Set whether this wallet broadcasts transactions. */
1074 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1076 /** Return whether transaction can be abandoned */
1077 bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1079 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1080 bool AbandonTransaction(const uint256& hashTx);
1082 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1083 bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1085 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1086 static CWallet* CreateWalletFromFile(const std::string walletFile);
1089 * Wallet post-init setup
1090 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1092 void postInitProcess(CScheduler& scheduler);
1094 bool BackupWallet(const std::string& strDest);
1096 /* Set the HD chain model (chain child index counters) */
1097 bool SetHDChain(const CHDChain& chain, bool memonly);
1098 const CHDChain& GetHDChain() const { return hdChain; }
1100 /* Returns true if HD is enabled */
1101 bool IsHDEnabled() const;
1103 /* Generates a new HD master key (will not be activated) */
1104 CPubKey GenerateNewHDMasterKey();
1106 /* Set the current HD master key (will reset the chain child index counters)
1107 Sets the master key's version based on the current wallet version (so the
1108 caller must ensure the current wallet version is correct before calling
1109 this function). */
1110 bool SetHDMasterKey(const CPubKey& key);
1113 /** A key allocated from the key pool. */
1114 class CReserveKey final : public CReserveScript
1116 protected:
1117 CWallet* pwallet;
1118 int64_t nIndex;
1119 CPubKey vchPubKey;
1120 bool fInternal;
1121 public:
1122 explicit CReserveKey(CWallet* pwalletIn)
1124 nIndex = -1;
1125 pwallet = pwalletIn;
1126 fInternal = false;
1129 CReserveKey() = default;
1130 CReserveKey(const CReserveKey&) = delete;
1131 CReserveKey& operator=(const CReserveKey&) = delete;
1133 ~CReserveKey()
1135 ReturnKey();
1138 void ReturnKey();
1139 bool GetReservedKey(CPubKey &pubkey, bool internal = false);
1140 void KeepKey();
1141 void KeepScript() override { KeepKey(); }
1145 /**
1146 * Account information.
1147 * Stored in wallet with key "acc"+string account name.
1149 class CAccount
1151 public:
1152 CPubKey vchPubKey;
1154 CAccount()
1156 SetNull();
1159 void SetNull()
1161 vchPubKey = CPubKey();
1164 ADD_SERIALIZE_METHODS;
1166 template <typename Stream, typename Operation>
1167 inline void SerializationOp(Stream& s, Operation ser_action) {
1168 int nVersion = s.GetVersion();
1169 if (!(s.GetType() & SER_GETHASH))
1170 READWRITE(nVersion);
1171 READWRITE(vchPubKey);
1175 // Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
1176 // ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
1177 // so that each entry corresponds to each vIn, in order.
1178 template <typename ContainerType>
1179 bool CWallet::DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const
1181 // Fill in dummy signatures for fee calculation.
1182 int nIn = 0;
1183 for (const auto& coin : coins)
1185 const CScript& scriptPubKey = coin.txout.scriptPubKey;
1186 SignatureData sigdata;
1188 if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata))
1190 return false;
1191 } else {
1192 UpdateTransaction(txNew, nIn, sigdata);
1195 nIn++;
1197 return true;
1200 #endif // BITCOIN_WALLET_WALLET_H