wallet: Display non-HD error on first run
[bitcoinplatinum.git] / src / wallet / wallet.h
blobc4af192f3634d36b03eb701e48389b7d7dfeb1e1
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 /** 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(nullptr);
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(nullptr);
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 // RelayWalletTransaction may only be called if fBroadcastTransactions!
474 bool RelayWalletTransaction(CConnman* connman);
476 std::set<uint256> GetConflicts() const;
480 class CInputCoin {
481 public:
482 CInputCoin(const CWalletTx* walletTx, unsigned int i)
484 if (!walletTx)
485 throw std::invalid_argument("walletTx should not be null");
486 if (i >= walletTx->tx->vout.size())
487 throw std::out_of_range("The output index is out of range");
489 outpoint = COutPoint(walletTx->GetHash(), i);
490 txout = walletTx->tx->vout[i];
493 COutPoint outpoint;
494 CTxOut txout;
496 bool operator<(const CInputCoin& rhs) const {
497 return outpoint < rhs.outpoint;
500 bool operator!=(const CInputCoin& rhs) const {
501 return outpoint != rhs.outpoint;
504 bool operator==(const CInputCoin& rhs) const {
505 return outpoint == rhs.outpoint;
509 class COutput
511 public:
512 const CWalletTx *tx;
513 int i;
514 int nDepth;
516 /** Whether we have the private keys to spend this output */
517 bool fSpendable;
519 /** Whether we know how to spend this output, ignoring the lack of keys */
520 bool fSolvable;
523 * Whether this output is considered safe to spend. Unconfirmed transactions
524 * from outside keys and unconfirmed replacement transactions are considered
525 * unsafe and will not be used to fund new spending transactions.
527 bool fSafe;
529 COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn)
531 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn;
534 std::string ToString() const;
540 /** Private key that includes an expiration date in case it never gets used. */
541 class CWalletKey
543 public:
544 CPrivKey vchPrivKey;
545 int64_t nTimeCreated;
546 int64_t nTimeExpires;
547 std::string strComment;
548 //! todo: add something to note what created it (user, getnewaddress, change)
549 //! maybe should have a map<string, string> property map
551 explicit CWalletKey(int64_t nExpires=0);
553 ADD_SERIALIZE_METHODS;
555 template <typename Stream, typename Operation>
556 inline void SerializationOp(Stream& s, Operation ser_action) {
557 int nVersion = s.GetVersion();
558 if (!(s.GetType() & SER_GETHASH))
559 READWRITE(nVersion);
560 READWRITE(vchPrivKey);
561 READWRITE(nTimeCreated);
562 READWRITE(nTimeExpires);
563 READWRITE(LIMITED_STRING(strComment, 65536));
568 * Internal transfers.
569 * Database key is acentry<account><counter>.
571 class CAccountingEntry
573 public:
574 std::string strAccount;
575 CAmount nCreditDebit;
576 int64_t nTime;
577 std::string strOtherAccount;
578 std::string strComment;
579 mapValue_t mapValue;
580 int64_t nOrderPos; //!< position in ordered transaction list
581 uint64_t nEntryNo;
583 CAccountingEntry()
585 SetNull();
588 void SetNull()
590 nCreditDebit = 0;
591 nTime = 0;
592 strAccount.clear();
593 strOtherAccount.clear();
594 strComment.clear();
595 nOrderPos = -1;
596 nEntryNo = 0;
599 ADD_SERIALIZE_METHODS;
601 template <typename Stream, typename Operation>
602 inline void SerializationOp(Stream& s, Operation ser_action) {
603 int nVersion = s.GetVersion();
604 if (!(s.GetType() & SER_GETHASH))
605 READWRITE(nVersion);
606 //! Note: strAccount is serialized as part of the key, not here.
607 READWRITE(nCreditDebit);
608 READWRITE(nTime);
609 READWRITE(LIMITED_STRING(strOtherAccount, 65536));
611 if (!ser_action.ForRead())
613 WriteOrderPos(nOrderPos, mapValue);
615 if (!(mapValue.empty() && _ssExtra.empty()))
617 CDataStream ss(s.GetType(), s.GetVersion());
618 ss.insert(ss.begin(), '\0');
619 ss << mapValue;
620 ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
621 strComment.append(ss.str());
625 READWRITE(LIMITED_STRING(strComment, 65536));
627 size_t nSepPos = strComment.find("\0", 0, 1);
628 if (ser_action.ForRead())
630 mapValue.clear();
631 if (std::string::npos != nSepPos)
633 CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), s.GetType(), s.GetVersion());
634 ss >> mapValue;
635 _ssExtra = std::vector<char>(ss.begin(), ss.end());
637 ReadOrderPos(nOrderPos, mapValue);
639 if (std::string::npos != nSepPos)
640 strComment.erase(nSepPos);
642 mapValue.erase("n");
645 private:
646 std::vector<char> _ssExtra;
650 /**
651 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
652 * and provides the ability to create new transactions.
654 class CWallet final : public CCryptoKeyStore, public CValidationInterface
656 private:
657 static std::atomic<bool> fFlushScheduled;
658 std::atomic<bool> fAbortRescan;
659 std::atomic<bool> fScanningWallet;
662 * Select a set of coins such that nValueRet >= nTargetValue and at least
663 * all coins from coinControl are selected; Never select unconfirmed coins
664 * if they are not ours
666 bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = nullptr) const;
668 CWalletDB *pwalletdbEncryption;
670 //! the current wallet version: clients below this version are not able to load the wallet
671 int nWalletVersion;
673 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
674 int nWalletMaxVersion;
676 int64_t nNextResend;
677 int64_t nLastResend;
678 bool fBroadcastTransactions;
681 * Used to keep track of spent outpoints, and
682 * detect and report conflicts (double-spends or
683 * mutated transactions where the mutant gets mined).
685 typedef std::multimap<COutPoint, uint256> TxSpends;
686 TxSpends mapTxSpends;
687 void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
688 void AddToSpends(const uint256& wtxid);
690 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
691 void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
693 void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
695 /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected.
696 * Should be called with pindexBlock and posInBlock if this is for a transaction that is included in a block. */
697 void SyncTransaction(const CTransactionRef& tx, const CBlockIndex *pindex = nullptr, int posInBlock = 0);
699 /* the HD chain data model (external chain counters) */
700 CHDChain hdChain;
702 /* HD derive new child key (on internal or external chain) */
703 void DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal = false);
705 std::set<int64_t> setInternalKeyPool;
706 std::set<int64_t> setExternalKeyPool;
707 int64_t m_max_keypool_index;
708 std::map<CKeyID, int64_t> m_pool_key_to_index;
710 int64_t nTimeFirstKey;
713 * Private version of AddWatchOnly method which does not accept a
714 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
715 * the watch key did not previously have a timestamp associated with it.
716 * Because this is an inherited virtual method, it is accessible despite
717 * being marked private, but it is marked private anyway to encourage use
718 * of the other AddWatchOnly which accepts a timestamp and sets
719 * nTimeFirstKey more intelligently for more efficient rescans.
721 bool AddWatchOnly(const CScript& dest) override;
723 std::unique_ptr<CWalletDBWrapper> dbw;
725 public:
727 * Main wallet lock.
728 * This lock protects all the fields added by CWallet.
730 mutable CCriticalSection cs_wallet;
732 /** Get database handle used by this wallet. Ideally this function would
733 * not be necessary.
735 CWalletDBWrapper& GetDBHandle()
737 return *dbw;
740 /** Get a name for this wallet for logging/debugging purposes.
742 std::string GetName() const
744 if (dbw) {
745 return dbw->GetName();
746 } else {
747 return "dummy";
751 void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool);
753 // Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
754 // key metadata.
755 std::map<CTxDestination, CKeyMetadata> mapKeyMetadata;
757 typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
758 MasterKeyMap mapMasterKeys;
759 unsigned int nMasterKeyMaxID;
761 // Create wallet with dummy database handle
762 CWallet(): dbw(new CWalletDBWrapper())
764 SetNull();
767 // Create wallet with passed-in database handle
768 explicit CWallet(std::unique_ptr<CWalletDBWrapper> dbw_in) : dbw(std::move(dbw_in))
770 SetNull();
773 ~CWallet()
775 delete pwalletdbEncryption;
776 pwalletdbEncryption = nullptr;
779 void SetNull()
781 nWalletVersion = FEATURE_BASE;
782 nWalletMaxVersion = FEATURE_BASE;
783 nMasterKeyMaxID = 0;
784 pwalletdbEncryption = nullptr;
785 nOrderPosNext = 0;
786 nAccountingEntryNumber = 0;
787 nNextResend = 0;
788 nLastResend = 0;
789 m_max_keypool_index = 0;
790 nTimeFirstKey = 0;
791 fBroadcastTransactions = false;
792 nRelockTime = 0;
793 fAbortRescan = false;
794 fScanningWallet = false;
797 std::map<uint256, CWalletTx> mapWallet;
798 std::list<CAccountingEntry> laccentries;
800 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
801 typedef std::multimap<int64_t, TxPair > TxItems;
802 TxItems wtxOrdered;
804 int64_t nOrderPosNext;
805 uint64_t nAccountingEntryNumber;
806 std::map<uint256, int> mapRequestCount;
808 std::map<CTxDestination, CAddressBookData> mapAddressBook;
810 std::set<COutPoint> setLockedCoins;
812 const CWalletTx* GetWalletTx(const uint256& hash) const;
814 //! check whether we are allowed to upgrade (or already support) to the named feature
815 bool CanSupportFeature(enum WalletFeature wf) const { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
818 * populate vCoins with vector of available COutputs.
820 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;
823 * Return list of available coins and locked coins grouped by non-change output address.
825 std::map<CTxDestination, std::vector<COutput>> ListCoins() const;
828 * Find non-change parent output.
830 const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const;
833 * Shuffle and select coins until nTargetValue is reached while avoiding
834 * small change; This method is stochastic for some inputs and upon
835 * completion the coin set and corresponding actual target value is
836 * assembled
838 bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const;
840 bool IsSpent(const uint256& hash, unsigned int n) const;
842 bool IsLockedCoin(uint256 hash, unsigned int n) const;
843 void LockCoin(const COutPoint& output);
844 void UnlockCoin(const COutPoint& output);
845 void UnlockAllCoins();
846 void ListLockedCoins(std::vector<COutPoint>& vOutpts) const;
849 * Rescan abort properties
851 void AbortRescan() { fAbortRescan = true; }
852 bool IsAbortingRescan() { return fAbortRescan; }
853 bool IsScanning() { return fScanningWallet; }
856 * keystore implementation
857 * Generate a new key
859 CPubKey GenerateNewKey(CWalletDB& walletdb, bool internal = false);
860 //! Adds a key to the store, and saves it to disk.
861 bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
862 bool AddKeyPubKeyWithDB(CWalletDB &walletdb,const CKey& key, const CPubKey &pubkey);
863 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
864 bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
865 //! Load metadata (used by LoadWallet)
866 bool LoadKeyMetadata(const CTxDestination& pubKey, const CKeyMetadata &metadata);
868 bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
869 void UpdateTimeFirstKey(int64_t nCreateTime);
871 //! Adds an encrypted key to the store, and saves it to disk.
872 bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) override;
873 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
874 bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
875 bool AddCScript(const CScript& redeemScript) override;
876 bool LoadCScript(const CScript& redeemScript);
878 //! Adds a destination data tuple to the store, and saves it to disk
879 bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
880 //! Erases a destination data tuple in the store and on disk
881 bool EraseDestData(const CTxDestination &dest, const std::string &key);
882 //! Adds a destination data tuple to the store, without saving it to disk
883 bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
884 //! Look up a destination data tuple in the store, return true if found false otherwise
885 bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
886 //! Get all destination values matching a prefix.
887 std::vector<std::string> GetDestValues(const std::string& prefix) const;
889 //! Adds a watch-only address to the store, and saves it to disk.
890 bool AddWatchOnly(const CScript& dest, int64_t nCreateTime);
891 bool RemoveWatchOnly(const CScript &dest) override;
892 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
893 bool LoadWatchOnly(const CScript &dest);
895 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
896 int64_t nRelockTime;
898 bool Unlock(const SecureString& strWalletPassphrase);
899 bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
900 bool EncryptWallet(const SecureString& strWalletPassphrase);
902 void GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const;
903 unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
905 /**
906 * Increment the next transaction order id
907 * @return next transaction order id
909 int64_t IncOrderPosNext(CWalletDB *pwalletdb = nullptr);
910 DBErrors ReorderTransactions();
911 bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment = "");
912 bool GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew = false);
914 void MarkDirty();
915 bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
916 bool LoadToWallet(const CWalletTx& wtxIn);
917 void TransactionAddedToMempool(const CTransactionRef& tx) override;
918 void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) override;
919 void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override;
920 bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate);
921 int64_t RescanFromTime(int64_t startTime, bool update);
922 CBlockIndex* ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
923 void ReacceptWalletTransactions();
924 void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman) override;
925 // ResendWalletTransactionsBefore may only be called if fBroadcastTransactions!
926 std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
927 CAmount GetBalance() const;
928 CAmount GetUnconfirmedBalance() const;
929 CAmount GetImmatureBalance() const;
930 CAmount GetWatchOnlyBalance() const;
931 CAmount GetUnconfirmedWatchOnlyBalance() const;
932 CAmount GetImmatureWatchOnlyBalance() const;
933 CAmount GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const;
934 CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
937 * Insert additional inputs into the transaction by
938 * calling CreateTransaction();
940 bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
941 bool SignTransaction(CMutableTransaction& tx);
944 * Create a new transaction paying the recipients with a set of coins
945 * selected by SelectCoins(); Also create the change output, when needed
946 * @note passing nChangePosInOut as -1 will result in setting a random position
948 bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
949 std::string& strFailReason, const CCoinControl& coin_control, bool sign = true);
950 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state);
952 void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries);
953 bool AddAccountingEntry(const CAccountingEntry&);
954 bool AddAccountingEntry(const CAccountingEntry&, CWalletDB *pwalletdb);
955 template <typename ContainerType>
956 bool DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const;
958 static CFeeRate minTxFee;
959 static CFeeRate fallbackFee;
960 static CFeeRate m_discard_rate;
962 bool NewKeyPool();
963 size_t KeypoolCountExternalKeys();
964 bool TopUpKeyPool(unsigned int kpSize = 0);
965 void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);
966 void KeepKey(int64_t nIndex);
967 void ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey);
968 bool GetKeyFromPool(CPubKey &key, bool internal = false);
969 int64_t GetOldestKeyPoolTime();
971 * Marks all keys in the keypool up to and including reserve_key as used.
973 void MarkReserveKeysAsUsed(int64_t keypool_id);
974 const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }
976 std::set< std::set<CTxDestination> > GetAddressGroupings();
977 std::map<CTxDestination, CAmount> GetAddressBalances();
979 std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
981 isminetype IsMine(const CTxIn& txin) const;
983 * Returns amount of debit if the input matches the
984 * filter, otherwise returns 0
986 CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
987 isminetype IsMine(const CTxOut& txout) const;
988 CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
989 bool IsChange(const CTxOut& txout) const;
990 CAmount GetChange(const CTxOut& txout) const;
991 bool IsMine(const CTransaction& tx) const;
992 /** should probably be renamed to IsRelevantToMe */
993 bool IsFromMe(const CTransaction& tx) const;
994 CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
995 /** Returns whether all of the inputs match the filter */
996 bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
997 CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
998 CAmount GetChange(const CTransaction& tx) const;
999 void SetBestChain(const CBlockLocator& loc) override;
1001 DBErrors LoadWallet(bool& fFirstRunRet);
1002 DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1003 DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut);
1005 bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1007 bool DelAddressBook(const CTxDestination& address);
1009 const std::string& GetAccountName(const CScript& scriptPubKey) const;
1011 void Inventory(const uint256 &hash) override
1014 LOCK(cs_wallet);
1015 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
1016 if (mi != mapRequestCount.end())
1017 (*mi).second++;
1021 void GetScriptForMining(std::shared_ptr<CReserveScript> &script);
1023 unsigned int GetKeyPoolSize()
1025 AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool
1026 return setInternalKeyPool.size() + setExternalKeyPool.size();
1029 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
1030 bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = nullptr, bool fExplicit = false);
1032 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
1033 bool SetMaxVersion(int nVersion);
1035 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
1036 int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1038 //! Get wallet transactions that conflict with given transaction (spend same outputs)
1039 std::set<uint256> GetConflicts(const uint256& txid) const;
1041 //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
1042 bool HasWalletSpend(const uint256& txid) const;
1044 //! Flush wallet (bitdb flush)
1045 void Flush(bool shutdown=false);
1047 /**
1048 * Address book entry changed.
1049 * @note called with lock cs_wallet held.
1051 boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1052 &address, const std::string &label, bool isMine,
1053 const std::string &purpose,
1054 ChangeType status)> NotifyAddressBookChanged;
1056 /**
1057 * Wallet transaction added, removed or updated.
1058 * @note called with lock cs_wallet held.
1060 boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1061 ChangeType status)> NotifyTransactionChanged;
1063 /** Show progress e.g. for rescan */
1064 boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1066 /** Watch-only address added */
1067 boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1069 /** Inquire whether this wallet broadcasts transactions. */
1070 bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1071 /** Set whether this wallet broadcasts transactions. */
1072 void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1074 /** Return whether transaction can be abandoned */
1075 bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1077 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1078 bool AbandonTransaction(const uint256& hashTx);
1080 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1081 bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1083 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1084 static CWallet* CreateWalletFromFile(const std::string walletFile);
1087 * Wallet post-init setup
1088 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1090 void postInitProcess(CScheduler& scheduler);
1092 bool BackupWallet(const std::string& strDest);
1094 /* Set the HD chain model (chain child index counters) */
1095 bool SetHDChain(const CHDChain& chain, bool memonly);
1096 const CHDChain& GetHDChain() const { return hdChain; }
1098 /* Returns true if HD is enabled */
1099 bool IsHDEnabled() const;
1101 /* Generates a new HD master key (will not be activated) */
1102 CPubKey GenerateNewHDMasterKey();
1104 /* Set the current HD master key (will reset the chain child index counters)
1105 Sets the master key's version based on the current wallet version (so the
1106 caller must ensure the current wallet version is correct before calling
1107 this function). */
1108 bool SetHDMasterKey(const CPubKey& key);
1111 /** A key allocated from the key pool. */
1112 class CReserveKey final : public CReserveScript
1114 protected:
1115 CWallet* pwallet;
1116 int64_t nIndex;
1117 CPubKey vchPubKey;
1118 bool fInternal;
1119 public:
1120 explicit CReserveKey(CWallet* pwalletIn)
1122 nIndex = -1;
1123 pwallet = pwalletIn;
1124 fInternal = false;
1127 CReserveKey() = default;
1128 CReserveKey(const CReserveKey&) = delete;
1129 CReserveKey& operator=(const CReserveKey&) = delete;
1131 ~CReserveKey()
1133 ReturnKey();
1136 void ReturnKey();
1137 bool GetReservedKey(CPubKey &pubkey, bool internal = false);
1138 void KeepKey();
1139 void KeepScript() override { KeepKey(); }
1143 /**
1144 * Account information.
1145 * Stored in wallet with key "acc"+string account name.
1147 class CAccount
1149 public:
1150 CPubKey vchPubKey;
1152 CAccount()
1154 SetNull();
1157 void SetNull()
1159 vchPubKey = CPubKey();
1162 ADD_SERIALIZE_METHODS;
1164 template <typename Stream, typename Operation>
1165 inline void SerializationOp(Stream& s, Operation ser_action) {
1166 int nVersion = s.GetVersion();
1167 if (!(s.GetType() & SER_GETHASH))
1168 READWRITE(nVersion);
1169 READWRITE(vchPubKey);
1173 // Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
1174 // ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
1175 // so that each entry corresponds to each vIn, in order.
1176 template <typename ContainerType>
1177 bool CWallet::DummySignTx(CMutableTransaction &txNew, const ContainerType &coins) const
1179 // Fill in dummy signatures for fee calculation.
1180 int nIn = 0;
1181 for (const auto& coin : coins)
1183 const CScript& scriptPubKey = coin.txout.scriptPubKey;
1184 SignatureData sigdata;
1186 if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata))
1188 return false;
1189 } else {
1190 UpdateTransaction(txNew, nIn, sigdata);
1193 nIn++;
1195 return true;
1198 #endif // BITCOIN_WALLET_WALLET_H