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 <util/message.h>
17 #include <util/strencodings.h>
18 #include <util/string.h>
19 #include <util/system.h>
20 #include <util/ui_change_type.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 std::vector<std::shared_ptr<CWallet>> GetWallets();
55 std::shared_ptr<CWallet> GetWallet(const std::string& name);
56 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const WalletLocation& location, bilingual_str& error, std::vector<bilingual_str>& warnings);
57 std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet);
58 
60  SUCCESS,
63 };
64 
65 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);
66 
70 static const CAmount DEFAULT_FALLBACK_FEE = 0;
72 static const CAmount DEFAULT_DISCARD_FEE = 10000;
74 static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
78 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
80 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
82 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
84 static const bool DEFAULT_WALLET_RBF = false;
85 static const bool DEFAULT_WALLETBROADCAST = true;
86 static const bool DEFAULT_DISABLE_WALLET = false;
90 constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
93 
95 static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
96 
97 class CCoinControl;
98 class COutput;
99 class CScript;
100 class CWalletTx;
101 struct FeeCalculation;
102 enum class FeeEstimateMode;
103 class ReserveDestination;
104 
107 
108 static constexpr uint64_t KNOWN_WALLET_FLAGS =
114 
115 static constexpr uint64_t MUTABLE_WALLET_FLAGS =
117 
118 static const std::map<std::string,WalletFlags> WALLET_FLAG_MAP{
119  {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
120  {"blank", WALLET_FLAG_BLANK_WALLET},
121  {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
122  {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
123  {"descriptor_wallet", WALLET_FLAG_DESCRIPTORS},
124 };
125 
126 extern const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS;
127 
144 {
145 protected:
147  const CWallet* const pwallet;
149  ScriptPubKeyMan* m_spk_man{nullptr};
152  int64_t nIndex{-1};
156  bool fInternal{false};
157 
158 public:
160  explicit ReserveDestination(CWallet* pwallet, OutputType type)
161  : pwallet(pwallet)
162  , type(type) { }
163 
164  ReserveDestination(const ReserveDestination&) = delete;
165  ReserveDestination& operator=(const ReserveDestination&) = delete;
166 
169  {
170  ReturnDestination();
171  }
172 
174  bool GetReservedDestination(CTxDestination& pubkey, bool internal);
176  void ReturnDestination();
178  void KeepDestination();
179 };
180 
183 {
184 private:
185  bool m_change{true};
186  std::string m_label;
187 public:
188  std::string purpose;
189 
190  CAddressBookData() : purpose("unknown") {}
191 
192  typedef std::map<std::string, std::string> StringMap;
193  StringMap destdata;
194 
195  bool IsChange() const { return m_change; }
196  const std::string& GetLabel() const { return m_label; }
197  void SetLabel(const std::string& label) {
198  m_change = false;
199  m_label = label;
200  }
201 };
202 
204 {
208 };
209 
210 typedef std::map<std::string, std::string> mapValue_t;
211 
212 
213 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
214 {
215  if (!mapValue.count("n"))
216  {
217  nOrderPos = -1; // TODO: calculate elsewhere
218  return;
219  }
220  nOrderPos = atoi64(mapValue["n"].c_str());
221 }
222 
223 
224 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
225 {
226  if (nOrderPos == -1)
227  return;
228  mapValue["n"] = ToString(nOrderPos);
229 }
230 
232 {
235  int vout;
236 };
237 
244 {
245 public:
246  template<typename Stream>
247  void Unserialize(Stream& s)
248  {
249  CTransactionRef tx;
250  uint256 hashBlock;
251  std::vector<uint256> vMerkleBranch;
252  int nIndex;
253 
254  s >> tx >> hashBlock >> vMerkleBranch >> nIndex;
255  }
256 };
257 
258 //Get the marginal bytes of spending the specified output
259 int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, bool use_max_sig = false);
260 
266 {
267 private:
268  const CWallet* pwallet;
269 
273  static const uint256 ABANDON_HASH;
274 
275 public:
302  std::vector<std::pair<std::string, std::string> > vOrderForm;
303  unsigned int fTimeReceivedIsTxTime;
304  unsigned int nTimeReceived;
305 
314  unsigned int nTimeSmart;
320  bool fFromMe;
321  int64_t nOrderPos;
322  std::multimap<int64_t, CWalletTx*>::const_iterator m_it_wtxOrdered;
323 
324  // memory only
325  enum AmountType { DEBIT, CREDIT, IMMATURE_CREDIT, AVAILABLE_CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
326  CAmount GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate = false) const;
327  mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
334  mutable bool m_is_cache_empty{true};
335  mutable bool fChangeCached;
336  mutable bool fInMempool;
338 
339  CWalletTx(const CWallet* wallet, CTransactionRef arg)
340  : pwallet(wallet),
341  tx(std::move(arg))
342  {
343  Init();
344  }
345 
346  void Init()
347  {
348  mapValue.clear();
349  vOrderForm.clear();
350  fTimeReceivedIsTxTime = false;
351  nTimeReceived = 0;
352  nTimeSmart = 0;
353  fFromMe = false;
354  fChangeCached = false;
355  fInMempool = false;
356  nChangeCached = 0;
357  nOrderPos = -1;
358  m_confirm = Confirmation{};
359  }
360 
362 
363  /* New transactions start as UNCONFIRMED. At BlockConnected,
364  * they will transition to CONFIRMED. In case of reorg, at BlockDisconnected,
365  * they roll back to UNCONFIRMED. If we detect a conflicting transaction at
366  * block connection, we update conflicted tx and its dependencies as CONFLICTED.
367  * If tx isn't confirmed and outside of mempool, the user may switch it to ABANDONED
368  * by using the abandontransaction call. This last status may be override by a CONFLICTED
369  * or CONFIRMED transition.
370  */
371  enum Status {
375  ABANDONED
376  };
377 
378  /* Confirmation includes tx status and a triplet of {block height/block hash/tx index in block}
379  * at which tx has been confirmed. All three are set to 0 if tx is unconfirmed or abandoned.
380  * Meaning of these fields changes with CONFLICTED state where they instead point to block hash
381  * and block height of the deepest conflicting tx.
382  */
383  struct Confirmation {
387  int nIndex;
388  Confirmation(Status s = UNCONFIRMED, int b = 0, uint256 h = uint256(), int i = 0) : status(s), block_height(b), hashBlock(h), nIndex(i) {}
389  };
390 
392 
393  template<typename Stream>
394  void Serialize(Stream& s) const
395  {
396  mapValue_t mapValueCopy = mapValue;
397 
398  mapValueCopy["fromaccount"] = "";
399  WriteOrderPos(nOrderPos, mapValueCopy);
400  if (nTimeSmart) {
401  mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
402  }
403 
404  std::vector<char> dummy_vector1;
405  std::vector<char> dummy_vector2;
406  bool dummy_bool = false;
407  uint256 serializedHash = isAbandoned() ? ABANDON_HASH : m_confirm.hashBlock;
408  int serializedIndex = isAbandoned() || isConflicted() ? -1 : m_confirm.nIndex;
409  s << tx << serializedHash << dummy_vector1 << serializedIndex << dummy_vector2 << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << dummy_bool;
410  }
411 
412  template<typename Stream>
413  void Unserialize(Stream& s)
414  {
415  Init();
416 
417  std::vector<uint256> dummy_vector1;
418  std::vector<CMerkleTx> dummy_vector2;
419  bool dummy_bool;
420  int serializedIndex;
421  s >> tx >> m_confirm.hashBlock >> dummy_vector1 >> serializedIndex >> dummy_vector2 >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> dummy_bool;
422 
423  /* At serialization/deserialization, an nIndex == -1 means that hashBlock refers to
424  * the earliest block in the chain we know this or any in-wallet ancestor conflicts
425  * with. If nIndex == -1 and hashBlock is ABANDON_HASH, it means transaction is abandoned.
426  * In same context, an nIndex >= 0 refers to a confirmed transaction (if hashBlock set) or
427  * unconfirmed one. Older clients interpret nIndex == -1 as unconfirmed for backward
428  * compatibility (pre-commit 9ac63d6).
429  */
430  if (serializedIndex == -1 && m_confirm.hashBlock == ABANDON_HASH) {
431  setAbandoned();
432  } else if (serializedIndex == -1) {
433  setConflicted();
434  } else if (!m_confirm.hashBlock.IsNull()) {
435  m_confirm.nIndex = serializedIndex;
436  setConfirmed();
437  }
438 
439  ReadOrderPos(nOrderPos, mapValue);
440  nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
441 
442  mapValue.erase("fromaccount");
443  mapValue.erase("spent");
444  mapValue.erase("n");
445  mapValue.erase("timesmart");
446  }
447 
449  {
450  tx = std::move(arg);
451  }
452 
454  void MarkDirty()
455  {
456  m_amounts[DEBIT].Reset();
457  m_amounts[CREDIT].Reset();
458  m_amounts[IMMATURE_CREDIT].Reset();
459  m_amounts[AVAILABLE_CREDIT].Reset();
460  fChangeCached = false;
461  m_is_cache_empty = true;
462  }
463 
465  CAmount GetDebit(const isminefilter& filter) const;
466  CAmount GetCredit(const isminefilter& filter) const;
467  CAmount GetImmatureCredit(bool fUseCache = true) const;
468  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
469  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The
470  // annotation "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid
471  // having to resolve the issue of member access into incomplete type CWallet.
472  CAmount GetAvailableCredit(bool fUseCache = true, const isminefilter& filter = ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS;
473  CAmount GetImmatureWatchOnlyCredit(const bool fUseCache = true) const;
474  CAmount GetChange() const;
475 
476  // Get the marginal bytes if spending the specified output from this transaction
477  int GetSpendSize(unsigned int out, bool use_max_sig = false) const
478  {
479  return CalculateMaximumSignedInputSize(tx->vout[out], pwallet, use_max_sig);
480  }
481 
482  void GetAmounts(std::list<COutputEntry>& listReceived,
483  std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const;
484 
485  bool IsFromMe(const isminefilter& filter) const
486  {
487  return (GetDebit(filter) > 0);
488  }
489 
490  // True if only scriptSigs are different
491  bool IsEquivalentTo(const CWalletTx& tx) const;
492 
493  bool InMempool() const;
494  bool IsTrusted() const;
495  bool IsTrusted(std::set<uint256>& trusted_parents) const;
496 
497  int64_t GetTxTime() const;
498 
499  // Pass this transaction to node for mempool insertion and relay to peers if flag set to true
500  bool SubmitMemoryPoolAndRelay(std::string& err_string, bool relay);
501 
502  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
503  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
504  // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
505  // resolve the issue of member access into incomplete type CWallet. Note
506  // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
507  // in place.
508  std::set<uint256> GetConflicts() const NO_THREAD_SAFETY_ANALYSIS;
509 
516  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
517  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
518  // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
519  // resolve the issue of member access into incomplete type CWallet. Note
520  // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
521  // in place.
522  int GetDepthInMainChain() const NO_THREAD_SAFETY_ANALYSIS;
523  bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
524 
530  int GetBlocksToMaturity() const;
531  bool isAbandoned() const { return m_confirm.status == CWalletTx::ABANDONED; }
533  {
534  m_confirm.status = CWalletTx::ABANDONED;
535  m_confirm.hashBlock = uint256();
536  m_confirm.block_height = 0;
537  m_confirm.nIndex = 0;
538  }
539  bool isConflicted() const { return m_confirm.status == CWalletTx::CONFLICTED; }
541  bool isUnconfirmed() const { return m_confirm.status == CWalletTx::UNCONFIRMED; }
543  bool isConfirmed() const { return m_confirm.status == CWalletTx::CONFIRMED; }
544  void setConfirmed() { m_confirm.status = CWalletTx::CONFIRMED; }
545  const uint256& GetHash() const { return tx->GetHash(); }
546  bool IsCoinBase() const { return tx->IsCoinBase(); }
547  bool IsImmatureCoinBase() const;
548 
549  // Disable copying of CWalletTx objects to prevent bugs where instances get
550  // copied in and out of the mapWallet map, and fields are updated in the
551  // wrong copy.
552  CWalletTx(CWalletTx const &) = delete;
553  void operator=(CWalletTx const &x) = delete;
554 };
555 
556 class COutput
557 {
558 public:
559  const CWalletTx *tx;
560  int i;
561  int nDepth;
562 
565 
568 
570  bool fSolvable;
571 
574 
580  bool fSafe;
581 
582  COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in = false)
583  {
584  tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn; nInputBytes = -1; use_max_sig = use_max_sig_in;
585  // If known and signable by the given wallet, compute nInputBytes
586  // Failure will keep this value -1
587  if (fSpendable && tx) {
588  nInputBytes = tx->GetSpendSize(i, use_max_sig);
589  }
590  }
591 
592  std::string ToString() const;
593 
594  inline CInputCoin GetInputCoin() const
595  {
596  return CInputCoin(tx->tx, i, nInputBytes);
597  }
598 };
599 
601 {
602  bool use_bnb = true;
603  size_t change_output_size = 0;
604  size_t change_spend_size = 0;
605  CFeeRate effective_fee = CFeeRate(0);
606  size_t tx_noinputs_size = 0;
608  bool m_subtract_fee_outputs = false;
609 
610  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) {}
612 };
613 
614 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
619 {
620 private:
621  CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
622 
623 
624  bool Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys = false);
625 
626  std::atomic<bool> fAbortRescan{false};
627  std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
628  std::atomic<int64_t> m_scanning_start{0};
629  std::atomic<double> m_scanning_progress{0};
630  friend class WalletRescanReserver;
631 
633  int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
634 
636  int nWalletMaxVersion GUARDED_BY(cs_wallet) = FEATURE_BASE;
637 
638  int64_t nNextResend = 0;
639  bool fBroadcastTransactions = false;
640  // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
641  std::atomic<int64_t> m_best_block_time {0};
642 
648  typedef std::multimap<COutPoint, uint256> TxSpends;
649  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
650  void AddToSpends(const COutPoint& outpoint, const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
651  void AddToSpends(const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
652 
666  bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
667 
668  /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
669  void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
670 
671  /* Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
672  void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
673 
674  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
675 
676  /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
677  * Should be called with non-zero block_hash and posInBlock if this is for a transaction that is included in a block. */
678  void SyncTransaction(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool update_tx = true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
679 
680  std::atomic<uint64_t> m_wallet_flags{0};
681 
682  bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose);
683 
685  void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
686 
688  void UnsetBlankWalletFlag(WalletBatch& batch) override;
689 
692 
695 
697  std::unique_ptr<WalletDatabase> database;
698 
706  uint256 m_last_block_processed GUARDED_BY(cs_wallet);
707 
708  /* Height of last block processed is used by wallet to know depth of transactions
709  * without relying on Chain interface beyond asynchronous updates. For safety, we
710  * initialize it to -1. Height is a pointer on node's tip and doesn't imply
711  * that the wallet has scanned sequentially all blocks up to this one.
712  */
713  int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
714 
715  std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
716  std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
717 
718  // Indexed by a unique identifier produced by each ScriptPubKeyMan using
719  // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
720  std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
721 
722 public:
723  /*
724  * Main wallet lock.
725  * This lock protects all the fields added by CWallet.
726  */
728 
733  {
734  return *database;
735  }
736  WalletDatabase& GetDatabase() override { return *database; }
737 
743  bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet,
744  const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
745 
746  const WalletLocation& GetLocation() const { return m_location; }
747 
750  const std::string& GetName() const { return m_location.GetName(); }
751 
752  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
753  MasterKeyMap mapMasterKeys;
754  unsigned int nMasterKeyMaxID = 0;
755 
757  CWallet(interfaces::Chain* chain, const WalletLocation& location, std::unique_ptr<WalletDatabase> database)
758  : m_chain(chain),
759  m_location(location),
760  database(std::move(database))
761  {
762  }
763 
765  {
766  // Should not have slots connected at this point.
767  assert(NotifyUnload.empty());
768  }
769 
770  bool IsCrypted() const;
771  bool IsLocked() const override;
772  bool Lock();
773 
775  bool HaveChain() const { return m_chain ? true : false; }
776 
777  std::map<uint256, CWalletTx> mapWallet GUARDED_BY(cs_wallet);
778 
779  typedef std::multimap<int64_t, CWalletTx*> TxItems;
780  TxItems wtxOrdered;
781 
782  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
783  uint64_t nAccountingEntryNumber = 0;
784 
785  std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
786  const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
787 
788  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
789 
791  std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
792 
794  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
795 
796  const CWalletTx* GetWalletTx(const uint256& hash) const;
797 
799  bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
800 
804  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);
805 
809  std::map<CTxDestination, std::vector<COutput>> ListCoins() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
810 
814  const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
815 
822  bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
823  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const;
824 
825  bool IsSpent(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
826 
827  // Whether this or any known UTXO with the same single key has been spent.
828  bool IsSpentKey(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
829  void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
830 
831  std::vector<OutputGroup> GroupOutputs(const std::vector<COutput>& outputs, bool single_coin, const size_t max_ancestors) const;
832 
833  bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
834  void LockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
835  void UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
836  void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
837  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
838 
839  /*
840  * Rescan abort properties
841  */
842  void AbortRescan() { fAbortRescan = true; }
843  bool IsAbortingRescan() const { return fAbortRescan; }
844  bool IsScanning() const { return fScanningWallet; }
845  int64_t ScanningDuration() const { return fScanningWallet ? GetTimeMillis() - m_scanning_start : 0; }
846  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
847 
849  void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
850 
851  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
852 
857  bool AddDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
859  bool EraseDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
861  void LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
863  bool GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
865  std::vector<std::string> GetDestValues(const std::string& prefix) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
866 
868  int64_t nRelockTime GUARDED_BY(cs_wallet){0};
869 
870  // Used to prevent concurrent calls to walletpassphrase RPC.
872  bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
873  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
874  bool EncryptWallet(const SecureString& strWalletPassphrase);
875 
876  void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
877  unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
878 
883  int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
884  DBErrors ReorderTransactions();
885 
886  void MarkDirty();
887 
894  using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
895 
896  CWalletTx* AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true);
897  bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
898  void transactionAddedToMempool(const CTransactionRef& tx) override;
899  void blockConnected(const CBlock& block, int height) override;
900  void blockDisconnected(const CBlock& block, int height) override;
901  void updatedBlockTip() override;
902  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
903 
904  struct ScanResult {
905  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
906 
912 
918  };
919  ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, Optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate);
920  void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override;
921  void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
922  void ResendWalletTransactions();
923  struct Balance {
924  CAmount m_mine_trusted{0};
925  CAmount m_mine_untrusted_pending{0};
926  CAmount m_mine_immature{0};
927  CAmount m_watchonly_trusted{0};
928  CAmount m_watchonly_untrusted_pending{0};
929  CAmount m_watchonly_immature{0};
930  };
931  Balance GetBalance(int min_depth = 0, bool avoid_reuse = true) const;
932  CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
933 
934  OutputType TransactionChangeType(const Optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend);
935 
940  bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
941  // Fetch the inputs and sign with SIGHASH_ALL.
943  // Sign the tx given the input coins and sighash.
944  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const;
945  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
946 
961  bool& complete,
962  int sighash_type = 1 /* SIGHASH_ALL */,
963  bool sign = true,
964  bool bip32derivs = true,
965  size_t* n_signed = nullptr) const;
966 
972  bool CreateTransaction(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, const CCoinControl& coin_control, bool sign = true);
982  void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
983 
984  bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, bool use_max_sig = false) const
985  {
986  std::vector<CTxOut> v_txouts(txouts.size());
987  std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
988  return DummySignTx(txNew, v_txouts, use_max_sig);
989  }
990  bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig = false) const;
991  bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig = false) const;
992 
993  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
994  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
995  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);
996  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);
997 
999  unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
1000  bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
1001  bool m_signal_rbf{DEFAULT_WALLET_RBF};
1002  bool m_allow_fallback_fee{true};
1004 
1011  OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
1018  Optional<OutputType> m_default_change_type{};
1020  CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
1021 
1022  size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1023  bool TopUpKeyPool(unsigned int kpSize = 0);
1024 
1025  int64_t GetOldestKeyPoolTime() const;
1026 
1027  std::set<std::set<CTxDestination>> GetAddressGroupings() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1028  std::map<CTxDestination, CAmount> GetAddressBalances() const;
1029 
1030  std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
1031 
1036  void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1037 
1038  bool GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error);
1039  bool GetNewChangeDestination(const OutputType type, CTxDestination& dest, std::string& error);
1040 
1041  isminetype IsMine(const CTxDestination& dest) const;
1042  isminetype IsMine(const CScript& script) const;
1043  isminetype IsMine(const CTxIn& txin) const;
1048  CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1049  isminetype IsMine(const CTxOut& txout) const;
1050  CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1051  bool IsChange(const CTxOut& txout) const;
1052  bool IsChange(const CScript& script) const;
1053  CAmount GetChange(const CTxOut& txout) const;
1054  bool IsMine(const CTransaction& tx) const;
1056  bool IsFromMe(const CTransaction& tx) const;
1057  CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1059  bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1060  CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1061  CAmount GetChange(const CTransaction& tx) const;
1062  void chainStateFlushed(const CBlockLocator& loc) override;
1063 
1064  DBErrors LoadWallet(bool& fFirstRunRet);
1065  DBErrors ZapWalletTx(std::list<CWalletTx>& vWtx);
1066  DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1067 
1068  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1069 
1070  bool DelAddressBook(const CTxDestination& address);
1071 
1072  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1073 
1075  void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr, bool fExplicit = false) override;
1076 
1078  bool SetMaxVersion(int nVersion);
1079 
1081  int GetVersion() const { LOCK(cs_wallet); return nWalletVersion; }
1082 
1084  std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1085 
1087  bool HasWalletSpend(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1088 
1090  void Flush();
1091 
1093  void Close();
1094 
1096  boost::signals2::signal<void ()> NotifyUnload;
1097 
1102  boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1103  &address, const std::string &label, bool isMine,
1104  const std::string &purpose,
1106 
1111  boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1113 
1115  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1116 
1118  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1119 
1121  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
1122 
1127  boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
1128 
1130  bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1132  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1133 
1135  bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1136 
1137  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1138  bool AbandonTransaction(const uint256& hashTx);
1139 
1141  bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1142 
1144  static bool Verify(interfaces::Chain& chain, const WalletLocation& location, bilingual_str& error_string, std::vector<bilingual_str>& warnings);
1145 
1146  /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1147  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);
1148 
1153  void postInitProcess();
1154 
1155  bool BackupWallet(const std::string& strDest) const;
1156 
1157  /* Returns true if HD is enabled */
1158  bool IsHDEnabled() const;
1159 
1160  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
1161  bool CanGetAddresses(bool internal = false) const;
1162 
1169  void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(cs_main, cs_wallet);
1170 
1172  void SetWalletFlag(uint64_t flags);
1173 
1175  void UnsetWalletFlag(uint64_t flag);
1176 
1178  bool IsWalletFlagSet(uint64_t flag) const override;
1179 
1182  bool AddWalletFlags(uint64_t flags);
1184  bool LoadWalletFlags(uint64_t flags);
1185 
1187  bool IsLegacy() const;
1188 
1190  const std::string GetDisplayName() const override {
1191  std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
1192  return strprintf("[%s]", wallet_name);
1193  };
1194 
1196  template<typename... Params>
1197  void WalletLogPrintf(std::string fmt, Params... parameters) const {
1198  LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
1199  };
1200 
1202  bool UpgradeWallet(int version, bilingual_str& error, std::vector<bilingual_str>& warnings);
1203 
1205  std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
1206 
1208  std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
1209 
1211  ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
1212 
1214  ScriptPubKeyMan* GetScriptPubKeyMan(const CScript& script) const;
1216  ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
1217 
1219  std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script, SignatureData& sigdata) const;
1220 
1222  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
1223  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
1224 
1226  LegacyScriptPubKeyMan* GetLegacyScriptPubKeyMan() const;
1227  LegacyScriptPubKeyMan* GetOrCreateLegacyScriptPubKeyMan();
1228 
1230  void SetupLegacyScriptPubKeyMan();
1231 
1232  const CKeyingMaterial& GetEncryptionKey() const override;
1233  bool HasEncryptionKeys() const override;
1234 
1236  int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1237  {
1238  AssertLockHeld(cs_wallet);
1239  assert(m_last_block_processed_height >= 0);
1240  return m_last_block_processed_height;
1241  };
1242  uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1243  {
1244  AssertLockHeld(cs_wallet);
1245  assert(m_last_block_processed_height >= 0);
1246  return m_last_block_processed;
1247  }
1249  void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1250  {
1251  AssertLockHeld(cs_wallet);
1252  m_last_block_processed_height = block_height;
1253  m_last_block_processed = block_hash;
1254  };
1255 
1257  void ConnectScriptPubKeyManNotifiers();
1258 
1260  void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc);
1261 
1266  void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1267 
1272  void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1273 
1275  void SetupDescriptorScriptPubKeyMans();
1276 
1278  DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1279 
1281  ScriptPubKeyMan* AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label);
1282 };
1283 
1288 void MaybeResendWalletTxs();
1289 
1292 {
1293 private:
1296 public:
1297  explicit WalletRescanReserver(CWallet& w) : m_wallet(w), m_could_reserve(false) {}
1298 
1299  bool reserve()
1300  {
1301  assert(!m_could_reserve);
1302  if (m_wallet.fScanningWallet.exchange(true)) {
1303  return false;
1304  }
1305  m_wallet.m_scanning_start = GetTimeMillis();
1306  m_wallet.m_scanning_progress = 0;
1307  m_could_reserve = true;
1308  return true;
1309  }
1310 
1311  bool isReserved() const
1312  {
1313  return (m_could_reserve && m_wallet.fScanningWallet);
1314  }
1315 
1317  {
1318  if (m_could_reserve) {
1319  m_wallet.fScanningWallet = false;
1320  }
1321  }
1322 };
1323 
1324 // Calculate the size of the transaction assuming all signatures are max size
1325 // Use DummySignatureCreator, which inserts 71 byte signatures everywhere.
1326 // NOTE: this requires that all inputs must be in mapWallet (eg the tx should
1327 // be IsAllFromMe).
1328 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig = false) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);
1329 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig = false);
1330 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:389
AmountType
Definition: wallet.h:325
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Definition: wallet.h:894
bool fChangeCached
Definition: wallet.h:335
const CWallet * pwallet
Definition: wallet.h:268
std::atomic< bool > fScanningWallet
Definition: wallet.h:627
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:55
std::unique_ptr< WalletDatabase > database
Internal database handle.
Definition: wallet.h:697
void Init()
Definition: wallet.h:346
int i
Definition: wallet.h:560
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:210
bool fSolvable
Whether we know how to spend this output, ignoring the lack of keys.
Definition: wallet.h:570
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:88
bool isConfirmed() const
Definition: wallet.h:543
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:1121
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:92
CTxDestination address
The destination.
Definition: wallet.h:154
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:716
CAmount nChangeCached
Definition: wallet.h:337
Bilingual messages:
Definition: translation.h:16
constexpr CAmount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:68
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:196
#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:485
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:984
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:910
void setAbandoned()
Definition: wallet.h:532
bool use_max_sig
Whether to use the maximum sized, 72 byte signature when calculating the size of the input spend...
Definition: wallet.h:573
static const CAmount COIN
Definition: amount.h:14
SigningResult
Definition: message.h:42
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:57
TxItems wtxOrdered
Definition: wallet.h:780
const char * prefix
Definition: rest.cpp:670
CWallet(interfaces::Chain *chain, const WalletLocation &location, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:757
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:648
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:321
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: wallet.h:322
bool isConflicted() const
Definition: wallet.h:539
bool IsInMainChain() const
Definition: wallet.h:523
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:213
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:43
int nWalletVersion GUARDED_BY(cs_wallet)
the current wallet version: clients below this version are not able to load the wallet ...
Definition: wallet.h:633
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:86
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:454
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:365
bool fSubtractFeeFromAmount
Definition: wallet.h:207
A version of CTransaction with the PSBT format.
Definition: psbt.h:390
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:752
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const WalletLocation &location, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:174
int nInputBytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: wallet.h:564
bool IsCoinBase() const
Definition: wallet.h:546
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:126
int64_t ScanningDuration() const
Definition: wallet.h:845
WalletCreationStatus
Definition: wallet.h:59
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:1127
CWallet & m_wallet
Definition: wallet.h:1294
bool isUnconfirmed() const
Definition: wallet.h:541
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:44
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:715
bool fSpendable
Whether we have the private keys to spend this output.
Definition: wallet.h:567
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:1236
bool IsNull() const
Definition: uint256.h:30
std::string purpose
Definition: wallet.h:188
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:320
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:84
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:846
WalletDatabase & GetDatabase() override
Definition: wallet.h:736
CWalletTx(const CWallet *wallet, CTransactionRef arg)
Definition: wallet.h:339
Access to the wallet database.
Definition: walletdb.h:177
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:301
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:1096
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:70
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:1112
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:1132
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:582
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:118
void Unserialize(Stream &s)
Definition: wallet.h:413
CScript scriptPubKey
Definition: wallet.h:205
Mutex m_unlock_mutex
Definition: wallet.h:868
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned, only used at serialization/deserializat...
Definition: wallet.h:273
int nDepth
Definition: wallet.h:561
const std::string & GetName() const
Get wallet name.
Definition: walletutil.h:81
Confirmation m_confirm
Definition: wallet.h:391
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:1197
An input of a transaction.
Definition: transaction.h:59
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *pwallet, bool use_max_sig=false)
Definition: wallet.cpp:1575
#define LOCK(cs)
Definition: sync.h:228
const char * name
Definition: rest.cpp:41
void SetTx(CTransactionRef arg)
Definition: wallet.h:448
bool IsChange() const
Definition: wallet.h:195
Chain notifications.
Definition: chain.h:240
bool fSafe
Whether this output is considered safe to spend.
Definition: wallet.h:580
CAmount amount
Definition: wallet.h:234
FeeEstimateMode
Definition: feerate.h:18
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:128
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:691
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:85
std::map< std::string, std::string > StringMap
Definition: wallet.h:192
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:732
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
Definition: wallet.h:160
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:1242
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:775
void setConflicted()
Definition: wallet.h:540
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:78
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:106
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:1249
An output of a transaction.
Definition: transaction.h:122
const WalletLocation & GetLocation() const
Definition: wallet.h:746
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:86
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:82
const uint256 & GetHash() const
Definition: wallet.h:545
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:20
std::string m_label
Definition: wallet.h:186
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:303
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey&#39;ed, it will be returned to the keypool...
Definition: wallet.h:168
CAmount nAmount
Definition: wallet.h:206
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1291
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:265
OutputType const type
Definition: wallet.h:150
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:720
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:1130
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:115
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:68
void Serialize(Stream &s) const
Definition: wallet.h:394
int flags
Definition: bitcoin-tx.cpp:509
bool fInMempool
Definition: wallet.h:336
void setConfirmed()
Definition: wallet.h:544
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:80
static void NotifyUnload(WalletModel *walletModel)
256-bit opaque blob.
Definition: uint256.h:123
void setUnconfirmed()
Definition: wallet.h:542
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:53
WalletLocation m_location
Wallet location which includes wallet name (see WalletLocation).
Definition: wallet.h:694
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:74
static void WriteOrderPos(const int64_t &nOrderPos, mapValue_t &mapValue)
Definition: wallet.h:224
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:52
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:1105
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:750
MasterKeyMap mapMasterKeys
Definition: wallet.h:753
int vout
Definition: wallet.h:235
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:82
void FundTransaction(CWallet *const pwallet, CMutableTransaction &tx, CAmount &fee_out, int &change_position, UniValue options, CCoinControl &coinControl)
Definition: rpcwallet.cpp:2917
Address book data.
Definition: wallet.h:182
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:1081
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:193
CTxDestination destination
Definition: wallet.h:233
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:314
CInputCoin GetInputCoin() const
Definition: wallet.h:594
void Reset()
Definition: ismine.h:39
int GetSpendSize(unsigned int out, bool use_max_sig=false) const
Definition: wallet.h:477
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:20
void Unserialize(Stream &s)
Definition: wallet.h:247
const CWalletTx * tx
Definition: wallet.h:559
void SetLabel(const std::string &label)
Definition: wallet.h:197
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:610
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:618
TransactionError
Definition: error.h:22
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:2059
A wrapper to reserve an address from a wallet.
Definition: wallet.h:143
void AbortRescan()
Definition: wallet.h:842
Definition: wallet.h:231
#define GUARDED_BY(x)
Definition: threadsafety.h:40
RecursiveMutex cs_wallet
Definition: wallet.h:727
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:1115
bool IsScanning() const
Definition: wallet.h:844
Optional< int > last_scanned_height
Definition: wallet.h:911
A mutable version of CTransaction.
Definition: transaction.h:347
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:917
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:799
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:76
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:851
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:628
unsigned int nTimeReceived
time received by this node
Definition: wallet.h:304
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:253
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
bool isAbandoned() const
Definition: wallet.h:531
bool isReserved() const
Definition: wallet.h:1311
Confirmation(Status s=UNCONFIRMED, int b=0, uint256 h=uint256(), int i=0)
Definition: wallet.h:388
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:212
std::atomic< double > m_scanning_progress
Definition: wallet.h:629
ChangeType
General change type (added, updated, removed).
Definition: ui_change_type.h:9
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:1118
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:779
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:147
WalletRescanReserver(CWallet &w)
Definition: wallet.h:1297
static const CAmount DEFAULT_DISCARD_FEE
-discardfee default
Definition: wallet.h:72
CTransactionRef tx
Definition: wallet.h:361
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig=false) EXCLUSIVE_LOCKS_REQUIRED(wallet -> cs_wallet)
Definition: wallet.cpp:1550
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:71
Legacy class used for deserializing vtxPrev for backwards compatibility.
Definition: wallet.h:243
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:108
~CWallet()
Definition: wallet.h:764
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:90
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:302
bool IsAbortingRescan() const
Definition: wallet.h:843
An instance of this class represents one database.
Definition: db.h:104
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:95