Bitcoin Core  0.20.99
P2P Digital Currency
wallet.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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.
5 
6 #ifndef BITCOIN_WALLET_WALLET_H
7 #define BITCOIN_WALLET_WALLET_H
8 
9 #include <amount.h>
10 #include <interfaces/chain.h>
11 #include <interfaces/handler.h>
12 #include <outputtype.h>
13 #include <policy/feerate.h>
14 #include <psbt.h>
15 #include <tinyformat.h>
16 #include <ui_interface.h>
17 #include <util/message.h>
18 #include <util/strencodings.h>
19 #include <util/string.h>
20 #include <util/system.h>
21 #include <validationinterface.h>
22 #include <wallet/coinselection.h>
23 #include <wallet/crypter.h>
24 #include <wallet/scriptpubkeyman.h>
25 #include <wallet/walletdb.h>
26 #include <wallet/walletutil.h>
27 
28 #include <algorithm>
29 #include <atomic>
30 #include <map>
31 #include <memory>
32 #include <set>
33 #include <stdexcept>
34 #include <stdint.h>
35 #include <string>
36 #include <utility>
37 #include <vector>
38 
39 #include <boost/signals2/signal.hpp>
40 
41 using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
42 
43 struct bilingual_str;
44 
50 void UnloadWallet(std::shared_ptr<CWallet>&& wallet);
51 
52 bool AddWallet(const std::shared_ptr<CWallet>& wallet);
53 bool RemoveWallet(const std::shared_ptr<CWallet>& wallet);
54 bool HasWallets();
55 std::vector<std::shared_ptr<CWallet>> GetWallets();
56 std::shared_ptr<CWallet> GetWallet(const std::string& name);
57 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const WalletLocation& location, bilingual_str& error, std::vector<bilingual_str>& warnings);
58 std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet);
59 
61  SUCCESS,
64 };
65 
66 WalletCreationStatus CreateWallet(interfaces::Chain& chain, const SecureString& passphrase, uint64_t wallet_creation_flags, const std::string& name, bilingual_str& error, std::vector<bilingual_str>& warnings, std::shared_ptr<CWallet>& result);
67 
71 static const CAmount DEFAULT_FALLBACK_FEE = 0;
73 static const CAmount DEFAULT_DISCARD_FEE = 10000;
75 static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
79 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
81 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
83 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
85 static const bool DEFAULT_WALLET_RBF = false;
86 static const bool DEFAULT_WALLETBROADCAST = true;
87 static const bool DEFAULT_DISABLE_WALLET = false;
91 constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
94 
96 static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
97 
98 class CCoinControl;
99 class COutput;
100 class CScript;
101 class CWalletTx;
102 struct FeeCalculation;
103 enum class FeeEstimateMode;
104 class ReserveDestination;
105 
108 
111 
112 static constexpr uint64_t KNOWN_WALLET_FLAGS =
118 
119 static constexpr uint64_t MUTABLE_WALLET_FLAGS =
121 
122 static const std::map<std::string,WalletFlags> WALLET_FLAG_MAP{
123  {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
124  {"blank", WALLET_FLAG_BLANK_WALLET},
125  {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
126  {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
127  {"descriptor_wallet", WALLET_FLAG_DESCRIPTORS},
128 };
129 
130 extern const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS;
131 
148 {
149 protected:
151  const CWallet* const pwallet;
153  ScriptPubKeyMan* m_spk_man{nullptr};
156  int64_t nIndex{-1};
160  bool fInternal{false};
161 
162 public:
164  explicit ReserveDestination(CWallet* pwallet, OutputType type)
165  : pwallet(pwallet)
166  , type(type) { }
167 
168  ReserveDestination(const ReserveDestination&) = delete;
169  ReserveDestination& operator=(const ReserveDestination&) = delete;
170 
173  {
174  ReturnDestination();
175  }
176 
178  bool GetReservedDestination(CTxDestination& pubkey, bool internal);
180  void ReturnDestination();
182  void KeepDestination();
183 };
184 
187 {
188 private:
189  bool m_change{true};
190  std::string m_label;
191 public:
192  std::string purpose;
193 
194  CAddressBookData() : purpose("unknown") {}
195 
196  typedef std::map<std::string, std::string> StringMap;
197  StringMap destdata;
198 
199  bool IsChange() const { return m_change; }
200  const std::string& GetLabel() const { return m_label; }
201  void SetLabel(const std::string& label) {
202  m_change = false;
203  m_label = label;
204  }
205 };
206 
208 {
212 };
213 
214 typedef std::map<std::string, std::string> mapValue_t;
215 
216 
217 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
218 {
219  if (!mapValue.count("n"))
220  {
221  nOrderPos = -1; // TODO: calculate elsewhere
222  return;
223  }
224  nOrderPos = atoi64(mapValue["n"].c_str());
225 }
226 
227 
228 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
229 {
230  if (nOrderPos == -1)
231  return;
232  mapValue["n"] = ToString(nOrderPos);
233 }
234 
236 {
239  int vout;
240 };
241 
248 {
249 public:
250  template<typename Stream>
251  void Unserialize(Stream& s)
252  {
253  CTransactionRef tx;
254  uint256 hashBlock;
255  std::vector<uint256> vMerkleBranch;
256  int nIndex;
257 
258  s >> tx >> hashBlock >> vMerkleBranch >> nIndex;
259  }
260 };
261 
262 //Get the marginal bytes of spending the specified output
263 int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, bool use_max_sig = false);
264 
270 {
271 private:
272  const CWallet* pwallet;
273 
277  static const uint256 ABANDON_HASH;
278 
279 public:
306  std::vector<std::pair<std::string, std::string> > vOrderForm;
307  unsigned int fTimeReceivedIsTxTime;
308  unsigned int nTimeReceived;
309 
318  unsigned int nTimeSmart;
324  bool fFromMe;
325  int64_t nOrderPos;
326  std::multimap<int64_t, CWalletTx*>::const_iterator m_it_wtxOrdered;
327 
328  // memory only
329  enum AmountType { DEBIT, CREDIT, IMMATURE_CREDIT, AVAILABLE_CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
330  CAmount GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate = false) const;
331  mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
338  mutable bool m_is_cache_empty{true};
339  mutable bool fChangeCached;
340  mutable bool fInMempool;
342 
343  CWalletTx(const CWallet* wallet, CTransactionRef arg)
344  : pwallet(wallet),
345  tx(std::move(arg))
346  {
347  Init();
348  }
349 
350  void Init()
351  {
352  mapValue.clear();
353  vOrderForm.clear();
354  fTimeReceivedIsTxTime = false;
355  nTimeReceived = 0;
356  nTimeSmart = 0;
357  fFromMe = false;
358  fChangeCached = false;
359  fInMempool = false;
360  nChangeCached = 0;
361  nOrderPos = -1;
362  m_confirm = Confirmation{};
363  }
364 
366 
367  /* New transactions start as UNCONFIRMED. At BlockConnected,
368  * they will transition to CONFIRMED. In case of reorg, at BlockDisconnected,
369  * they roll back to UNCONFIRMED. If we detect a conflicting transaction at
370  * block connection, we update conflicted tx and its dependencies as CONFLICTED.
371  * If tx isn't confirmed and outside of mempool, the user may switch it to ABANDONED
372  * by using the abandontransaction call. This last status may be override by a CONFLICTED
373  * or CONFIRMED transition.
374  */
375  enum Status {
379  ABANDONED
380  };
381 
382  /* Confirmation includes tx status and a triplet of {block height/block hash/tx index in block}
383  * at which tx has been confirmed. All three are set to 0 if tx is unconfirmed or abandoned.
384  * Meaning of these fields changes with CONFLICTED state where they instead point to block hash
385  * and block height of the deepest conflicting tx.
386  */
387  struct Confirmation {
391  int nIndex;
392  Confirmation(Status s = UNCONFIRMED, int b = 0, uint256 h = uint256(), int i = 0) : status(s), block_height(b), hashBlock(h), nIndex(i) {}
393  };
394 
396 
397  template<typename Stream>
398  void Serialize(Stream& s) const
399  {
400  mapValue_t mapValueCopy = mapValue;
401 
402  mapValueCopy["fromaccount"] = "";
403  WriteOrderPos(nOrderPos, mapValueCopy);
404  if (nTimeSmart) {
405  mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
406  }
407 
408  std::vector<char> dummy_vector1;
409  std::vector<char> dummy_vector2;
410  bool dummy_bool = false;
411  uint256 serializedHash = isAbandoned() ? ABANDON_HASH : m_confirm.hashBlock;
412  int serializedIndex = isAbandoned() || isConflicted() ? -1 : m_confirm.nIndex;
413  s << tx << serializedHash << dummy_vector1 << serializedIndex << dummy_vector2 << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << dummy_bool;
414  }
415 
416  template<typename Stream>
417  void Unserialize(Stream& s)
418  {
419  Init();
420 
421  std::vector<uint256> dummy_vector1;
422  std::vector<CMerkleTx> dummy_vector2;
423  bool dummy_bool;
424  int serializedIndex;
425  s >> tx >> m_confirm.hashBlock >> dummy_vector1 >> serializedIndex >> dummy_vector2 >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> dummy_bool;
426 
427  /* At serialization/deserialization, an nIndex == -1 means that hashBlock refers to
428  * the earliest block in the chain we know this or any in-wallet ancestor conflicts
429  * with. If nIndex == -1 and hashBlock is ABANDON_HASH, it means transaction is abandoned.
430  * In same context, an nIndex >= 0 refers to a confirmed transaction (if hashBlock set) or
431  * unconfirmed one. Older clients interpret nIndex == -1 as unconfirmed for backward
432  * compatibility (pre-commit 9ac63d6).
433  */
434  if (serializedIndex == -1 && m_confirm.hashBlock == ABANDON_HASH) {
435  setAbandoned();
436  } else if (serializedIndex == -1) {
437  setConflicted();
438  } else if (!m_confirm.hashBlock.IsNull()) {
439  m_confirm.nIndex = serializedIndex;
440  setConfirmed();
441  }
442 
443  ReadOrderPos(nOrderPos, mapValue);
444  nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
445 
446  mapValue.erase("fromaccount");
447  mapValue.erase("spent");
448  mapValue.erase("n");
449  mapValue.erase("timesmart");
450  }
451 
453  {
454  tx = std::move(arg);
455  }
456 
458  void MarkDirty()
459  {
460  m_amounts[DEBIT].Reset();
461  m_amounts[CREDIT].Reset();
462  m_amounts[IMMATURE_CREDIT].Reset();
463  m_amounts[AVAILABLE_CREDIT].Reset();
464  fChangeCached = false;
465  m_is_cache_empty = true;
466  }
467 
469  CAmount GetDebit(const isminefilter& filter) const;
470  CAmount GetCredit(const isminefilter& filter) const;
471  CAmount GetImmatureCredit(bool fUseCache = true) const;
472  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
473  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The
474  // annotation "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid
475  // having to resolve the issue of member access into incomplete type CWallet.
476  CAmount GetAvailableCredit(bool fUseCache = true, const isminefilter& filter = ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS;
477  CAmount GetImmatureWatchOnlyCredit(const bool fUseCache = true) const;
478  CAmount GetChange() const;
479 
480  // Get the marginal bytes if spending the specified output from this transaction
481  int GetSpendSize(unsigned int out, bool use_max_sig = false) const
482  {
483  return CalculateMaximumSignedInputSize(tx->vout[out], pwallet, use_max_sig);
484  }
485 
486  void GetAmounts(std::list<COutputEntry>& listReceived,
487  std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const;
488 
489  bool IsFromMe(const isminefilter& filter) const
490  {
491  return (GetDebit(filter) > 0);
492  }
493 
494  // True if only scriptSigs are different
495  bool IsEquivalentTo(const CWalletTx& tx) const;
496 
497  bool InMempool() const;
498  bool IsTrusted() const;
499  bool IsTrusted(std::set<uint256>& trusted_parents) const;
500 
501  int64_t GetTxTime() const;
502 
503  // Pass this transaction to node for mempool insertion and relay to peers if flag set to true
504  bool SubmitMemoryPoolAndRelay(std::string& err_string, bool relay);
505 
506  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
507  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
508  // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
509  // resolve the issue of member access into incomplete type CWallet. Note
510  // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
511  // in place.
512  std::set<uint256> GetConflicts() const NO_THREAD_SAFETY_ANALYSIS;
513 
520  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
521  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
522  // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
523  // resolve the issue of member access into incomplete type CWallet. Note
524  // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
525  // in place.
526  int GetDepthInMainChain() const NO_THREAD_SAFETY_ANALYSIS;
527  bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
528 
534  int GetBlocksToMaturity() const;
535  bool isAbandoned() const { return m_confirm.status == CWalletTx::ABANDONED; }
537  {
538  m_confirm.status = CWalletTx::ABANDONED;
539  m_confirm.hashBlock = uint256();
540  m_confirm.block_height = 0;
541  m_confirm.nIndex = 0;
542  }
543  bool isConflicted() const { return m_confirm.status == CWalletTx::CONFLICTED; }
545  bool isUnconfirmed() const { return m_confirm.status == CWalletTx::UNCONFIRMED; }
547  bool isConfirmed() const { return m_confirm.status == CWalletTx::CONFIRMED; }
548  void setConfirmed() { m_confirm.status = CWalletTx::CONFIRMED; }
549  const uint256& GetHash() const { return tx->GetHash(); }
550  bool IsCoinBase() const { return tx->IsCoinBase(); }
551  bool IsImmatureCoinBase() const;
552 
553  // Disable copying of CWalletTx objects to prevent bugs where instances get
554  // copied in and out of the mapWallet map, and fields are updated in the
555  // wrong copy.
556  CWalletTx(CWalletTx const &) = delete;
557  void operator=(CWalletTx const &x) = delete;
558 };
559 
560 class COutput
561 {
562 public:
563  const CWalletTx *tx;
564  int i;
565  int nDepth;
566 
569 
572 
574  bool fSolvable;
575 
578 
584  bool fSafe;
585 
586  COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in = false)
587  {
588  tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn; nInputBytes = -1; use_max_sig = use_max_sig_in;
589  // If known and signable by the given wallet, compute nInputBytes
590  // Failure will keep this value -1
591  if (fSpendable && tx) {
592  nInputBytes = tx->GetSpendSize(i, use_max_sig);
593  }
594  }
595 
596  std::string ToString() const;
597 
598  inline CInputCoin GetInputCoin() const
599  {
600  return CInputCoin(tx->tx, i, nInputBytes);
601  }
602 };
603 
605 {
606  bool use_bnb = true;
607  size_t change_output_size = 0;
608  size_t change_spend_size = 0;
609  CFeeRate effective_fee = CFeeRate(0);
610  size_t tx_noinputs_size = 0;
612  bool m_subtract_fee_outputs = false;
613 
614  CoinSelectionParams(bool use_bnb, size_t change_output_size, size_t change_spend_size, CFeeRate effective_fee, size_t tx_noinputs_size) : use_bnb(use_bnb), change_output_size(change_output_size), change_spend_size(change_spend_size), effective_fee(effective_fee), tx_noinputs_size(tx_noinputs_size) {}
616 };
617 
618 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
623 {
624 private:
625  CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
626 
627 
628  bool Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys = false);
629 
630  std::atomic<bool> fAbortRescan{false};
631  std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
632  std::atomic<int64_t> m_scanning_start{0};
633  std::atomic<double> m_scanning_progress{0};
634  std::mutex mutexScanning;
635  friend class WalletRescanReserver;
636 
638  int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
639 
641  int nWalletMaxVersion GUARDED_BY(cs_wallet) = FEATURE_BASE;
642 
643  int64_t nNextResend = 0;
644  bool fBroadcastTransactions = false;
645  // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
646  std::atomic<int64_t> m_best_block_time {0};
647 
653  typedef std::multimap<COutPoint, uint256> TxSpends;
654  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
655  void AddToSpends(const COutPoint& outpoint, const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
656  void AddToSpends(const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
657 
671  bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
672 
673  /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
674  void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
675 
676  /* Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
677  void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
678 
679  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
680 
681  /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
682  * Should be called with non-zero block_hash and posInBlock if this is for a transaction that is included in a block. */
683  void SyncTransaction(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool update_tx = true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
684 
685  std::atomic<uint64_t> m_wallet_flags{0};
686 
687  bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose);
688 
690  void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
691 
693  void UnsetBlankWalletFlag(WalletBatch& batch) override;
694 
697 
700 
702  std::unique_ptr<WalletDatabase> database;
703 
711  uint256 m_last_block_processed GUARDED_BY(cs_wallet);
712 
713  /* Height of last block processed is used by wallet to know depth of transactions
714  * without relying on Chain interface beyond asynchronous updates. For safety, we
715  * initialize it to -1. Height is a pointer on node's tip and doesn't imply
716  * that the wallet has scanned sequentially all blocks up to this one.
717  */
718  int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
719 
720  std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
721  std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
722 
723  // Indexed by a unique identifier produced by each ScriptPubKeyMan using
724  // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
725  std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
726 
727 public:
728  /*
729  * Main wallet lock.
730  * This lock protects all the fields added by CWallet.
731  */
733 
738  {
739  return *database;
740  }
741  WalletDatabase& GetDatabase() override { return *database; }
742 
748  bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet,
749  const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
750 
751  const WalletLocation& GetLocation() const { return m_location; }
752 
755  const std::string& GetName() const { return m_location.GetName(); }
756 
757  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
758  MasterKeyMap mapMasterKeys;
759  unsigned int nMasterKeyMaxID = 0;
760 
762  CWallet(interfaces::Chain* chain, const WalletLocation& location, std::unique_ptr<WalletDatabase> database)
763  : m_chain(chain),
764  m_location(location),
765  database(std::move(database))
766  {
767  }
768 
770  {
771  // Should not have slots connected at this point.
772  assert(NotifyUnload.empty());
773  }
774 
775  bool IsCrypted() const;
776  bool IsLocked() const override;
777  bool Lock();
778 
780  bool HaveChain() const { return m_chain ? true : false; }
781 
782  std::map<uint256, CWalletTx> mapWallet GUARDED_BY(cs_wallet);
783 
784  typedef std::multimap<int64_t, CWalletTx*> TxItems;
785  TxItems wtxOrdered;
786 
787  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
788  uint64_t nAccountingEntryNumber = 0;
789 
790  std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
791  const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
792 
793  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
794 
796  std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
797 
799  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
800 
801  const CWalletTx* GetWalletTx(const uint256& hash) const;
802 
804  bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
805 
809  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 EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
810 
814  std::map<CTxDestination, std::vector<COutput>> ListCoins() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
815 
819  const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
820 
827  bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
828  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const;
829 
830  bool IsSpent(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
831 
832  // Whether this or any known UTXO with the same single key has been spent.
833  bool IsSpentKey(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
834  void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
835 
836  std::vector<OutputGroup> GroupOutputs(const std::vector<COutput>& outputs, bool single_coin, const size_t max_ancestors) const;
837 
838  bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
839  void LockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
840  void UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
841  void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
842  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
843 
844  /*
845  * Rescan abort properties
846  */
847  void AbortRescan() { fAbortRescan = true; }
848  bool IsAbortingRescan() const { return fAbortRescan; }
849  bool IsScanning() const { return fScanningWallet; }
850  int64_t ScanningDuration() const { return fScanningWallet ? GetTimeMillis() - m_scanning_start : 0; }
851  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
852 
854  void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
855 
856  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
857 
862  bool AddDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
864  bool EraseDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
866  void LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
868  bool GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
870  std::vector<std::string> GetDestValues(const std::string& prefix) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
871 
873  int64_t nRelockTime GUARDED_BY(cs_wallet){0};
874 
875  // Used to prevent concurrent calls to walletpassphrase RPC.
877  bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
878  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
879  bool EncryptWallet(const SecureString& strWalletPassphrase);
880 
881  void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
882  unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
883 
888  int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
889  DBErrors ReorderTransactions();
890 
891  void MarkDirty();
892 
899  using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
900 
901  CWalletTx* AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true);
902  bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
903  void transactionAddedToMempool(const CTransactionRef& tx) override;
904  void blockConnected(const CBlock& block, int height) override;
905  void blockDisconnected(const CBlock& block, int height) override;
906  void updatedBlockTip() override;
907  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
908 
909  struct ScanResult {
910  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
911 
917 
923  };
924  ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, Optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate);
925  void transactionRemovedFromMempool(const CTransactionRef &ptx) override;
926  void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
927  void ResendWalletTransactions();
928  struct Balance {
929  CAmount m_mine_trusted{0};
930  CAmount m_mine_untrusted_pending{0};
931  CAmount m_mine_immature{0};
932  CAmount m_watchonly_trusted{0};
933  CAmount m_watchonly_untrusted_pending{0};
934  CAmount m_watchonly_immature{0};
935  };
936  Balance GetBalance(int min_depth = 0, bool avoid_reuse = true) const;
937  CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
938 
939  OutputType TransactionChangeType(OutputType change_type, const std::vector<CRecipient>& vecSend);
940 
945  bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
946  // Fetch the inputs and sign with SIGHASH_ALL.
948  // Sign the tx given the input coins and sighash.
949  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const;
950  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
951 
966  bool& complete,
967  int sighash_type = 1 /* SIGHASH_ALL */,
968  bool sign = true,
969  bool bip32derivs = true) const;
970 
976  bool CreateTransaction(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, const CCoinControl& coin_control, bool sign = true);
986  void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
987 
988  bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, bool use_max_sig = false) const
989  {
990  std::vector<CTxOut> v_txouts(txouts.size());
991  std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
992  return DummySignTx(txNew, v_txouts, use_max_sig);
993  }
994  bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig = false) const;
995  bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig = false) const;
996 
997  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
998  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
999  bool ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1000  bool ImportScriptPubKeys(const std::string& label, const std::set<CScript>& script_pub_keys, const bool have_solving_data, const bool apply_label, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1001 
1003  unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
1004  bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
1005  bool m_signal_rbf{DEFAULT_WALLET_RBF};
1006  bool m_allow_fallback_fee{true};
1008 
1015  OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
1016  OutputType m_default_change_type{DEFAULT_CHANGE_TYPE};
1018  CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
1019 
1020  size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1021  bool TopUpKeyPool(unsigned int kpSize = 0);
1022 
1023  int64_t GetOldestKeyPoolTime() const;
1024 
1025  std::set<std::set<CTxDestination>> GetAddressGroupings() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1026  std::map<CTxDestination, CAmount> GetAddressBalances() const;
1027 
1028  std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
1029 
1034  void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1035 
1036  bool GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error);
1037  bool GetNewChangeDestination(const OutputType type, CTxDestination& dest, std::string& error);
1038 
1039  isminetype IsMine(const CTxDestination& dest) const;
1040  isminetype IsMine(const CScript& script) const;
1041  isminetype IsMine(const CTxIn& txin) const;
1046  CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1047  isminetype IsMine(const CTxOut& txout) const;
1048  CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1049  bool IsChange(const CTxOut& txout) const;
1050  bool IsChange(const CScript& script) const;
1051  CAmount GetChange(const CTxOut& txout) const;
1052  bool IsMine(const CTransaction& tx) const;
1054  bool IsFromMe(const CTransaction& tx) const;
1055  CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1057  bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1058  CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1059  CAmount GetChange(const CTransaction& tx) const;
1060  void chainStateFlushed(const CBlockLocator& loc) override;
1061 
1062  DBErrors LoadWallet(bool& fFirstRunRet);
1063  DBErrors ZapWalletTx(std::list<CWalletTx>& vWtx);
1064  DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1065 
1066  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1067 
1068  bool DelAddressBook(const CTxDestination& address);
1069 
1070  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1071 
1073  void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr, bool fExplicit = false) override;
1074 
1076  bool SetMaxVersion(int nVersion);
1077 
1079  int GetVersion() const { LOCK(cs_wallet); return nWalletVersion; }
1080 
1082  std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1083 
1085  bool HasWalletSpend(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1086 
1088  void Flush(bool shutdown=false);
1089 
1091  boost::signals2::signal<void ()> NotifyUnload;
1092 
1097  boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1098  &address, const std::string &label, bool isMine,
1099  const std::string &purpose,
1101 
1106  boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1108 
1110  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1111 
1113  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1114 
1116  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
1117 
1122  boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
1123 
1125  bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1127  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1128 
1130  bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1131 
1132  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1133  bool AbandonTransaction(const uint256& hashTx);
1134 
1136  bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1137 
1139  static bool Verify(interfaces::Chain& chain, const WalletLocation& location, bool salvage_wallet, bilingual_str& error_string, std::vector<bilingual_str>& warnings);
1140 
1141  /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1142  static std::shared_ptr<CWallet> CreateWalletFromFile(interfaces::Chain& chain, const WalletLocation& location, bilingual_str& error, std::vector<bilingual_str>& warnings, uint64_t wallet_creation_flags = 0);
1143 
1148  void postInitProcess();
1149 
1150  bool BackupWallet(const std::string& strDest) const;
1151 
1152  /* Returns true if HD is enabled */
1153  bool IsHDEnabled() const;
1154 
1155  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
1156  bool CanGetAddresses(bool internal = false) const;
1157 
1164  void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(cs_main, cs_wallet);
1165 
1167  void SetWalletFlag(uint64_t flags);
1168 
1170  void UnsetWalletFlag(uint64_t flag);
1171 
1173  bool IsWalletFlagSet(uint64_t flag) const override;
1174 
1177  bool SetWalletFlags(uint64_t overwriteFlags, bool memOnly);
1178 
1180  bool IsLegacy() const;
1181 
1183  const std::string GetDisplayName() const override {
1184  std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
1185  return strprintf("[%s]", wallet_name);
1186  };
1187 
1189  template<typename... Params>
1190  void WalletLogPrintf(std::string fmt, Params... parameters) const {
1191  LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
1192  };
1193 
1195  bool UpgradeWallet(int version, bilingual_str& error, std::vector<bilingual_str>& warnings);
1196 
1198  std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
1199 
1201  std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
1202 
1204  ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
1205 
1207  ScriptPubKeyMan* GetScriptPubKeyMan(const CScript& script) const;
1209  ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
1210 
1212  std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script, SignatureData& sigdata) const;
1213 
1215  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
1216  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
1217 
1219  LegacyScriptPubKeyMan* GetLegacyScriptPubKeyMan() const;
1220  LegacyScriptPubKeyMan* GetOrCreateLegacyScriptPubKeyMan();
1221 
1223  void SetupLegacyScriptPubKeyMan();
1224 
1225  const CKeyingMaterial& GetEncryptionKey() const override;
1226  bool HasEncryptionKeys() const override;
1227 
1229  int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1230  {
1231  AssertLockHeld(cs_wallet);
1232  assert(m_last_block_processed_height >= 0);
1233  return m_last_block_processed_height;
1234  };
1235  uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1236  {
1237  AssertLockHeld(cs_wallet);
1238  assert(m_last_block_processed_height >= 0);
1239  return m_last_block_processed;
1240  }
1242  void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1243  {
1244  AssertLockHeld(cs_wallet);
1245  m_last_block_processed_height = block_height;
1246  m_last_block_processed = block_hash;
1247  };
1248 
1250  void ConnectScriptPubKeyManNotifiers();
1251 
1253  void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc);
1254 
1260  void SetActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal, bool memonly = false);
1261 
1263  void SetupDescriptorScriptPubKeyMans();
1264 
1266  DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1267 
1269  ScriptPubKeyMan* AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label);
1270 };
1271 
1276 void MaybeResendWalletTxs();
1277 
1280 {
1281 private:
1284 public:
1285  explicit WalletRescanReserver(CWallet& w) : m_wallet(w), m_could_reserve(false) {}
1286 
1287  bool reserve()
1288  {
1289  assert(!m_could_reserve);
1290  std::lock_guard<std::mutex> lock(m_wallet.mutexScanning);
1291  if (m_wallet.fScanningWallet) {
1292  return false;
1293  }
1294  m_wallet.m_scanning_start = GetTimeMillis();
1295  m_wallet.m_scanning_progress = 0;
1296  m_wallet.fScanningWallet = true;
1297  m_could_reserve = true;
1298  return true;
1299  }
1300 
1301  bool isReserved() const
1302  {
1303  return (m_could_reserve && m_wallet.fScanningWallet);
1304  }
1305 
1307  {
1308  std::lock_guard<std::mutex> lock(m_wallet.mutexScanning);
1309  if (m_could_reserve) {
1310  m_wallet.fScanningWallet = false;
1311  }
1312  }
1313 };
1314 
1315 // Calculate the size of the transaction assuming all signatures are max size
1316 // Use DummySignatureCreator, which inserts 71 byte signatures everywhere.
1317 // NOTE: this requires that all inputs must be in mapWallet (eg the tx should
1318 // be IsAllFromMe).
1319 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig = false) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);
1320 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig = false);
1321 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:387
AmountType
Definition: wallet.h:329
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Definition: wallet.h:899
bool fChangeCached
Definition: wallet.h:339
const CWallet * pwallet
Definition: wallet.h:272
std::atomic< bool > fScanningWallet
Definition: wallet.h:631
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:53
std::unique_ptr< WalletDatabase > database
Internal database handle.
Definition: wallet.h:702
void Init()
Definition: wallet.h:350
int i
Definition: wallet.h:564
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:214
bool fSolvable
Whether we know how to spend this output, ignoring the lack of keys.
Definition: wallet.h:574
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:89
bool isConfirmed() const
Definition: wallet.h:547
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:114
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:1116
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:93
CTxDestination address
The destination.
Definition: wallet.h:158
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:721
CAmount nChangeCached
Definition: wallet.h:341
Bilingual messages:
Definition: translation.h:16
constexpr CAmount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:69
Definition: block.h:62
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:57
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:25
const std::string & GetLabel() const
Definition: wallet.h:200
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:489
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:988
constexpr OutputType DEFAULT_CHANGE_TYPE
Default for -changetype.
Definition: wallet.h:110
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:915
void setAbandoned()
Definition: wallet.h:536
bool use_max_sig
Whether to use the maximum sized, 72 byte signature when calculating the size of the input spend...
Definition: wallet.h:577
static const CAmount COIN
Definition: amount.h:14
SigningResult
Definition: message.h:42
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:56
FeeEstimateMode
Definition: fees.h:49
TxItems wtxOrdered
Definition: wallet.h:785
const char * prefix
Definition: rest.cpp:648
CWallet(interfaces::Chain *chain, const WalletLocation &location, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:762
std::multimap< COutPoint, uint256 > TxSpends
Used to keep track of spent outpoints, and detect and report conflicts (double-spends or mutated tran...
Definition: wallet.h:653
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:60
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:325
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: wallet.h:326
bool isConflicted() const
Definition: wallet.h:543
An instance of this class represents one database.
Definition: db.h:120
bool IsInMainChain() const
Definition: wallet.h:527
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:61
static void ReadOrderPos(int64_t &nOrderPos, mapValue_t &mapValue)
Definition: wallet.h:217
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:164
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:42
int nWalletVersion GUARDED_BY(cs_wallet)
the current wallet version: clients below this version are not able to load the wallet ...
Definition: wallet.h:638
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:87
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:458
bool fSubtractFeeFromAmount
Definition: wallet.h:211
A version of CTransaction with the PSBT format.
Definition: psbt.h:392
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:757
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const WalletLocation &location, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:153
int nInputBytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: wallet.h:568
bool IsCoinBase() const
Definition: wallet.h:550
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:129
int64_t ScanningDuration() const
Definition: wallet.h:850
WalletCreationStatus
Definition: wallet.h:60
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:1122
CWallet & m_wallet
Definition: wallet.h:1282
bool isUnconfirmed() const
Definition: wallet.h:545
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:46
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:720
bool fSpendable
Whether we have the private keys to spend this output.
Definition: wallet.h:571
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:1229
bool IsNull() const
Definition: uint256.h:30
std::string purpose
Definition: wallet.h:192
OutputType
Definition: outputtype.h:17
bool fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node...
Definition: wallet.h:324
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:85
Coin Control Features.
Definition: coincontrol.h:22
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:14
double ScanningProgress() const
Definition: wallet.h:851
WalletDatabase & GetDatabase() override
Definition: wallet.h:741
CWalletTx(const CWallet *wallet, CTransactionRef arg)
Definition: wallet.h:343
Access to the wallet database.
Definition: walletdb.h:179
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:305
std::mutex mutexScanning
Definition: wallet.h:634
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: dummywallet.cpp:87
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
boost::signals2::signal< void()> NotifyUnload
Wallet is about to be unloaded.
Definition: wallet.h:1091
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:71
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:1107
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:1127
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:69
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in=false)
Definition: wallet.h:586
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:122
void Unserialize(Stream &s)
Definition: wallet.h:417
CScript scriptPubKey
Definition: wallet.h:209
Mutex m_unlock_mutex
Definition: wallet.h:873
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned, only used at serialization/deserializat...
Definition: wallet.h:277
int nDepth
Definition: wallet.h:565
const std::string & GetName() const
Get wallet name.
Definition: walletutil.h:81
Confirmation m_confirm
Definition: wallet.h:395
ChangeType
General change type (added, updated, removed).
Definition: ui_interface.h:24
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Definition: wallet.h:1190
An input of a transaction.
Definition: transaction.h:57
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *pwallet, bool use_max_sig=false)
Definition: wallet.cpp:1524
#define LOCK(cs)
Definition: sync.h:218
const char * name
Definition: rest.cpp:41
void SetTx(CTransactionRef arg)
Definition: wallet.h:452
bool IsChange() const
Definition: wallet.h:199
Chain notifications.
Definition: chain.h:237
Chain & m_chain
Definition: wallet.cpp:508
bool fSafe
Whether this output is considered safe to spend.
Definition: wallet.h:584
CAmount amount
Definition: wallet.h:238
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:124
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:696
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:86
std::map< std::string, std::string > StringMap
Definition: wallet.h:196
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
Definition: walletutil.h:58
uint8_t isminefilter
Definition: wallet.h:34
WalletDatabase & GetDBHandle()
Get database handle used by this wallet.
Definition: wallet.h:737
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
Definition: wallet.h:164
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:1235
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:780
void setConflicted()
Definition: wallet.h:544
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:79
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:107
isminetype
IsMine() return codes.
Definition: ismine.h:18
void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Set last block processed height, currently only use in unit test.
Definition: wallet.h:1242
An output of a transaction.
Definition: transaction.h:120
const WalletLocation & GetLocation() const
Definition: wallet.h:751
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:91
Descriptor with some wallet metadata.
Definition: walletutil.h:91
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: dummywallet.cpp:86
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:83
const uint256 & GetHash() const
Definition: wallet.h:549
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
std::string m_label
Definition: wallet.h:190
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:307
Special output type for change outputs only.
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey&#39;ed, it will be returned to the keypool...
Definition: wallet.h:172
CAmount nAmount
Definition: wallet.h:210
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1279
bool HasWallets()
Definition: wallet.cpp:79
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:269
OutputType const type
Definition: wallet.h:154
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:725
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:1125
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:119
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:67
void Serialize(Stream &s) const
Definition: wallet.h:398
int flags
Definition: bitcoin-tx.cpp:509
bool fInMempool
Definition: wallet.h:340
void setConfirmed()
Definition: wallet.h:548
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:81
static void NotifyUnload(WalletModel *walletModel)
256-bit opaque blob.
Definition: uint256.h:120
void setUnconfirmed()
Definition: wallet.h:546
int64_t atoi64(const char *psz)
Cachable amount subdivided into watchonly and spendable parts.
Definition: ismine.h:34
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
WalletLocation m_location
Wallet location which includes wallet name (see WalletLocation).
Definition: wallet.h:699
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:75
static void WriteOrderPos(const int64_t &nOrderPos, mapValue_t &mapValue)
Definition: wallet.h:228
Result CommitTransaction(CWallet &wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:247
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), 0)
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:50
boost::signals2::signal< void(CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:1100
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:755
MasterKeyMap mapMasterKeys
Definition: wallet.h:758
int vout
Definition: wallet.h:239
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:79
Address book data.
Definition: wallet.h:186
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:1079
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
StringMap destdata
Definition: wallet.h:197
CTxDestination destination
Definition: wallet.h:237
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:318
CInputCoin GetInputCoin() const
Definition: wallet.h:598
void Reset()
Definition: ismine.h:39
int GetSpendSize(unsigned int out, bool use_max_sig=false) const
Definition: wallet.h:481
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:20
void Unserialize(Stream &s)
Definition: wallet.h:251
const CWalletTx * tx
Definition: wallet.h:563
void SetLabel(const std::string &label)
Definition: wallet.h:201
CoinSelectionParams(bool use_bnb, size_t change_output_size, size_t change_spend_size, CFeeRate effective_fee, size_t tx_noinputs_size)
Definition: wallet.h:614
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:622
TransactionError
Definition: error.h:22
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:2009
A wrapper to reserve an address from a wallet.
Definition: wallet.h:147
void AbortRescan()
Definition: wallet.h:847
Definition: wallet.h:235
#define GUARDED_BY(x)
Definition: threadsafety.h:38
void FundTransaction(CWallet *const pwallet, CMutableTransaction &tx, CAmount &fee_out, int &change_position, UniValue options)
Definition: rpcwallet.cpp:3008
RecursiveMutex cs_wallet
Definition: wallet.h:732
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:1110
bool IsScanning() const
Definition: wallet.h:849
Optional< int > last_scanned_height
Definition: wallet.h:916
A mutable version of CTransaction.
Definition: transaction.h:345
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:922
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we are allowed to upgrade (or already support) to the named feature ...
Definition: wallet.h:804
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:77
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:856
static std::vector< COutput > vCoins
The WalletLocation class provides wallet information.
Definition: walletutil.h:71
std::atomic< int64_t > m_scanning_start
Definition: wallet.h:632
unsigned int nTimeReceived
time received by this node
Definition: wallet.h:308
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:251
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
bool isAbandoned() const
Definition: wallet.h:535
bool isReserved() const
Definition: wallet.h:1301
Confirmation(Status s=UNCONFIRMED, int b=0, uint256 h=uint256(), int i=0)
Definition: wallet.h:392
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:143
std::atomic< double > m_scanning_progress
Definition: wallet.h:633
AssertLockHeld(g_cs_orphans)
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:61
WalletCreationStatus CreateWallet(interfaces::Chain &chain, const SecureString &passphrase, uint64_t wallet_creation_flags, const std::string &name, bilingual_str &error, std::vector< bilingual_str > &warnings, std::shared_ptr< CWallet > &result)
Definition: dummywallet.cpp:81
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:1113
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:784
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:151
WalletRescanReserver(CWallet &w)
Definition: wallet.h:1285
static const CAmount DEFAULT_DISCARD_FEE
-discardfee default
Definition: wallet.h:73
CTransactionRef tx
Definition: wallet.h:365
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig=false) EXCLUSIVE_LOCKS_REQUIRED(wallet -> cs_wallet)
Definition: wallet.cpp:1499
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:71
Legacy class used for deserializing vtxPrev for backwards compatibility.
Definition: wallet.h:247
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:112
~CWallet()
Definition: wallet.h:769
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:91
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:306
bool IsAbortingRescan() const
Definition: wallet.h:848
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:96