Bitcoin Core  0.21.1
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, Optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
54 bool RemoveWallet(const std::shared_ptr<CWallet>& wallet, Optional<bool> load_on_start);
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 std::string& name, Optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings);
58 std::shared_ptr<CWallet> CreateWallet(interfaces::Chain& chain, const std::string& name, Optional<bool> load_on_start, DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings);
59 std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet);
60 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
61 
65 static const CAmount DEFAULT_FALLBACK_FEE = 0;
67 static const CAmount DEFAULT_DISCARD_FEE = 10000;
69 static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
79 constexpr CAmount HIGH_APS_FEE{COIN / 10000};
83 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
85 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
87 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
89 static const bool DEFAULT_WALLET_RBF = false;
90 static const bool DEFAULT_WALLETBROADCAST = true;
91 static const bool DEFAULT_DISABLE_WALLET = false;
95 constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
98 
100 static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
101 
102 class CCoinControl;
103 class COutput;
104 class CScript;
105 class CWalletTx;
106 struct FeeCalculation;
107 enum class FeeEstimateMode;
108 class ReserveDestination;
109 
112 
113 static constexpr uint64_t KNOWN_WALLET_FLAGS =
119 
120 static constexpr uint64_t MUTABLE_WALLET_FLAGS =
122 
123 static const std::map<std::string,WalletFlags> WALLET_FLAG_MAP{
124  {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
125  {"blank", WALLET_FLAG_BLANK_WALLET},
126  {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
127  {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
128  {"descriptor_wallet", WALLET_FLAG_DESCRIPTORS},
129 };
130 
131 extern const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS;
132 
149 {
150 protected:
152  const CWallet* const pwallet;
157  int64_t nIndex{-1};
161  bool fInternal{false};
162 
163 public:
165  explicit ReserveDestination(CWallet* pwallet, OutputType type)
166  : pwallet(pwallet)
167  , type(type) { }
168 
169  ReserveDestination(const ReserveDestination&) = delete;
171 
174  {
176  }
177 
179  bool GetReservedDestination(CTxDestination& pubkey, bool internal);
181  void ReturnDestination();
183  void KeepDestination();
184 };
185 
188 {
189 private:
190  bool m_change{true};
191  std::string m_label;
192 public:
193  std::string purpose;
194 
195  CAddressBookData() : purpose("unknown") {}
196 
197  typedef std::map<std::string, std::string> StringMap;
198  StringMap destdata;
199 
200  bool IsChange() const { return m_change; }
201  const std::string& GetLabel() const { return m_label; }
202  void SetLabel(const std::string& label) {
203  m_change = false;
204  m_label = label;
205  }
206 };
207 
209 {
213 };
214 
215 typedef std::map<std::string, std::string> mapValue_t;
216 
217 
218 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
219 {
220  if (!mapValue.count("n"))
221  {
222  nOrderPos = -1; // TODO: calculate elsewhere
223  return;
224  }
225  nOrderPos = atoi64(mapValue["n"]);
226 }
227 
228 
229 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
230 {
231  if (nOrderPos == -1)
232  return;
233  mapValue["n"] = ToString(nOrderPos);
234 }
235 
237 {
240  int vout;
241 };
242 
249 {
250 public:
251  template<typename Stream>
252  void Unserialize(Stream& s)
253  {
254  CTransactionRef tx;
255  uint256 hashBlock;
256  std::vector<uint256> vMerkleBranch;
257  int nIndex;
258 
259  s >> tx >> hashBlock >> vMerkleBranch >> nIndex;
260  }
261 };
262 
263 //Get the marginal bytes of spending the specified output
264 int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, bool use_max_sig = false);
265 
271 {
272 private:
273  const CWallet* const pwallet;
274 
278  static constexpr const uint256& ABANDON_HASH = uint256::ONE;
279 
280 public:
307  std::vector<std::pair<std::string, std::string> > vOrderForm;
308  unsigned int fTimeReceivedIsTxTime;
309  unsigned int nTimeReceived;
310 
319  unsigned int nTimeSmart;
325  bool fFromMe;
326  int64_t nOrderPos;
327  std::multimap<int64_t, CWalletTx*>::const_iterator m_it_wtxOrdered;
328 
329  // memory only
330  enum AmountType { DEBIT, CREDIT, IMMATURE_CREDIT, AVAILABLE_CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
331  CAmount GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate = false) const;
332  mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
339  mutable bool m_is_cache_empty{true};
340  mutable bool fChangeCached;
341  mutable bool fInMempool;
343 
344  CWalletTx(const CWallet* wallet, CTransactionRef arg)
345  : pwallet(wallet),
346  tx(std::move(arg))
347  {
348  Init();
349  }
350 
351  void Init()
352  {
353  mapValue.clear();
354  vOrderForm.clear();
355  fTimeReceivedIsTxTime = false;
356  nTimeReceived = 0;
357  nTimeSmart = 0;
358  fFromMe = false;
359  fChangeCached = false;
360  fInMempool = false;
361  nChangeCached = 0;
362  nOrderPos = -1;
363  m_confirm = Confirmation{};
364  }
365 
367 
368  /* New transactions start as UNCONFIRMED. At BlockConnected,
369  * they will transition to CONFIRMED. In case of reorg, at BlockDisconnected,
370  * they roll back to UNCONFIRMED. If we detect a conflicting transaction at
371  * block connection, we update conflicted tx and its dependencies as CONFLICTED.
372  * If tx isn't confirmed and outside of mempool, the user may switch it to ABANDONED
373  * by using the abandontransaction call. This last status may be override by a CONFLICTED
374  * or CONFIRMED transition.
375  */
376  enum Status {
380  ABANDONED
381  };
382 
383  /* Confirmation includes tx status and a triplet of {block height/block hash/tx index in block}
384  * at which tx has been confirmed. All three are set to 0 if tx is unconfirmed or abandoned.
385  * Meaning of these fields changes with CONFLICTED state where they instead point to block hash
386  * and block height of the deepest conflicting tx.
387  */
388  struct Confirmation {
392  int nIndex;
393  Confirmation(Status s = UNCONFIRMED, int b = 0, uint256 h = uint256(), int i = 0) : status(s), block_height(b), hashBlock(h), nIndex(i) {}
394  };
395 
397 
398  template<typename Stream>
399  void Serialize(Stream& s) const
400  {
401  mapValue_t mapValueCopy = mapValue;
402 
403  mapValueCopy["fromaccount"] = "";
404  WriteOrderPos(nOrderPos, mapValueCopy);
405  if (nTimeSmart) {
406  mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
407  }
408 
409  std::vector<char> dummy_vector1;
410  std::vector<char> dummy_vector2;
411  bool dummy_bool = false;
412  uint256 serializedHash = isAbandoned() ? ABANDON_HASH : m_confirm.hashBlock;
413  int serializedIndex = isAbandoned() || isConflicted() ? -1 : m_confirm.nIndex;
414  s << tx << serializedHash << dummy_vector1 << serializedIndex << dummy_vector2 << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << dummy_bool;
415  }
416 
417  template<typename Stream>
418  void Unserialize(Stream& s)
419  {
420  Init();
421 
422  std::vector<uint256> dummy_vector1;
423  std::vector<CMerkleTx> dummy_vector2;
424  bool dummy_bool;
425  int serializedIndex;
426  s >> tx >> m_confirm.hashBlock >> dummy_vector1 >> serializedIndex >> dummy_vector2 >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> dummy_bool;
427 
428  /* At serialization/deserialization, an nIndex == -1 means that hashBlock refers to
429  * the earliest block in the chain we know this or any in-wallet ancestor conflicts
430  * with. If nIndex == -1 and hashBlock is ABANDON_HASH, it means transaction is abandoned.
431  * In same context, an nIndex >= 0 refers to a confirmed transaction (if hashBlock set) or
432  * unconfirmed one. Older clients interpret nIndex == -1 as unconfirmed for backward
433  * compatibility (pre-commit 9ac63d6).
434  */
435  if (serializedIndex == -1 && m_confirm.hashBlock == ABANDON_HASH) {
436  setAbandoned();
437  } else if (serializedIndex == -1) {
438  setConflicted();
439  } else if (!m_confirm.hashBlock.IsNull()) {
440  m_confirm.nIndex = serializedIndex;
441  setConfirmed();
442  }
443 
444  ReadOrderPos(nOrderPos, mapValue);
445  nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
446 
447  mapValue.erase("fromaccount");
448  mapValue.erase("spent");
449  mapValue.erase("n");
450  mapValue.erase("timesmart");
451  }
452 
454  {
455  tx = std::move(arg);
456  }
457 
459  void MarkDirty()
460  {
461  m_amounts[DEBIT].Reset();
462  m_amounts[CREDIT].Reset();
463  m_amounts[IMMATURE_CREDIT].Reset();
464  m_amounts[AVAILABLE_CREDIT].Reset();
465  fChangeCached = false;
466  m_is_cache_empty = true;
467  }
468 
470  CAmount GetDebit(const isminefilter& filter) const;
471  CAmount GetCredit(const isminefilter& filter) const;
472  CAmount GetImmatureCredit(bool fUseCache = true) const;
473  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
474  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The
475  // annotation "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid
476  // having to resolve the issue of member access into incomplete type CWallet.
477  CAmount GetAvailableCredit(bool fUseCache = true, const isminefilter& filter = ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS;
478  CAmount GetImmatureWatchOnlyCredit(const bool fUseCache = true) const;
479  CAmount GetChange() const;
480 
481  // Get the marginal bytes if spending the specified output from this transaction
482  int GetSpendSize(unsigned int out, bool use_max_sig = false) const
483  {
484  return CalculateMaximumSignedInputSize(tx->vout[out], pwallet, use_max_sig);
485  }
486 
487  void GetAmounts(std::list<COutputEntry>& listReceived,
488  std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const;
489 
490  bool IsFromMe(const isminefilter& filter) const
491  {
492  return (GetDebit(filter) > 0);
493  }
494 
495  // True if only scriptSigs are different
496  bool IsEquivalentTo(const CWalletTx& tx) const;
497 
498  bool InMempool() const;
499  bool IsTrusted() 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;
612  size_t tx_noinputs_size = 0;
614  bool m_subtract_fee_outputs = false;
615 
616  CoinSelectionParams(bool use_bnb, size_t change_output_size, size_t change_spend_size, CFeeRate effective_feerate,
617  CFeeRate long_term_feerate, CFeeRate discard_feerate, size_t tx_noinputs_size) :
618  use_bnb(use_bnb),
619  change_output_size(change_output_size),
620  change_spend_size(change_spend_size),
621  m_effective_feerate(effective_feerate),
622  m_long_term_feerate(long_term_feerate),
623  m_discard_feerate(discard_feerate),
624  tx_noinputs_size(tx_noinputs_size)
625  {}
627 };
628 
629 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
634 {
635 private:
636  CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
637 
638 
639  bool Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys = false);
640 
641  std::atomic<bool> fAbortRescan{false};
642  std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
643  std::atomic<int64_t> m_scanning_start{0};
644  std::atomic<double> m_scanning_progress{0};
645  friend class WalletRescanReserver;
646 
648  int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
649 
650  int64_t nNextResend = 0;
651  bool fBroadcastTransactions = false;
652  // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
653  std::atomic<int64_t> m_best_block_time {0};
654 
660  typedef std::multimap<COutPoint, uint256> TxSpends;
661  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
662  void AddToSpends(const COutPoint& outpoint, const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
663  void AddToSpends(const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
664 
678  bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
679 
680  /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
681  void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
682 
683  /* Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
684  void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
685 
686  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
687 
688  /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
689  * Should be called with non-zero block_hash and posInBlock if this is for a transaction that is included in a block. */
690  void SyncTransaction(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool update_tx = true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
691 
692  std::atomic<uint64_t> m_wallet_flags{0};
693 
694  bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose);
695 
697  void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
698 
700  void UnsetBlankWalletFlag(WalletBatch& batch) override;
701 
704 
706  std::string m_name;
707 
709  std::unique_ptr<WalletDatabase> database;
710 
718  uint256 m_last_block_processed GUARDED_BY(cs_wallet);
719 
720  /* Height of last block processed is used by wallet to know depth of transactions
721  * without relying on Chain interface beyond asynchronous updates. For safety, we
722  * initialize it to -1. Height is a pointer on node's tip and doesn't imply
723  * that the wallet has scanned sequentially all blocks up to this one.
724  */
725  int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
726 
727  std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
728  std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
729 
730  // Indexed by a unique identifier produced by each ScriptPubKeyMan using
731  // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
732  std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
733 
734  bool CreateTransactionInternal(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, const CCoinControl& coin_control, FeeCalculation& fee_calc_out, bool sign);
735 
736 public:
737  /*
738  * Main wallet lock.
739  * This lock protects all the fields added by CWallet.
740  */
742 
747  {
748  return *database;
749  }
750  WalletDatabase& GetDatabase() const override { return *database; }
751 
757  bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet,
758  const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
759 
762  const std::string& GetName() const { return m_name; }
763 
764  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
765  MasterKeyMap mapMasterKeys;
766  unsigned int nMasterKeyMaxID = 0;
767 
769  CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database)
770  : m_chain(chain),
771  m_name(name),
772  database(std::move(database))
773  {
774  }
775 
777  {
778  // Should not have slots connected at this point.
779  assert(NotifyUnload.empty());
780  }
781 
782  bool IsCrypted() const;
783  bool IsLocked() const override;
784  bool Lock();
785 
787  bool HaveChain() const { return m_chain ? true : false; }
788 
789  std::map<uint256, CWalletTx> mapWallet GUARDED_BY(cs_wallet);
790 
791  typedef std::multimap<int64_t, CWalletTx*> TxItems;
792  TxItems wtxOrdered;
793 
794  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
795  uint64_t nAccountingEntryNumber = 0;
796 
797  std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
798  const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
799 
800  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
801 
803  std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
804 
806  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
807 
808  const CWalletTx* GetWalletTx(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
809  bool IsTrusted(const CWalletTx& wtx, std::set<uint256>& trusted_parents) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
810 
812  bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return IsFeatureSupported(nWalletVersion, wf); }
813 
817  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);
818 
822  std::map<CTxDestination, std::vector<COutput>> ListCoins() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
823 
827  const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
828 
835  bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
836  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const;
837 
838  bool IsSpent(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
839 
840  // Whether this or any known UTXO with the same single key has been spent.
841  bool IsSpentKey(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
842  void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
843 
844  std::vector<OutputGroup> GroupOutputs(const std::vector<COutput>& outputs, bool single_coin, const size_t max_ancestors) const;
845 
846  bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
847  void LockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
848  void UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
849  void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
850  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
851 
852  /*
853  * Rescan abort properties
854  */
855  void AbortRescan() { fAbortRescan = true; }
856  bool IsAbortingRescan() const { return fAbortRescan; }
857  bool IsScanning() const { return fScanningWallet; }
858  int64_t ScanningDuration() const { return fScanningWallet ? GetTimeMillis() - m_scanning_start : 0; }
859  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
860 
862  void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
863 
864  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; return true; }
865 
870  bool AddDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
872  bool EraseDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
874  void LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
876  bool GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
878  std::vector<std::string> GetDestValues(const std::string& prefix) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
879 
881  int64_t nRelockTime GUARDED_BY(cs_wallet){0};
882 
883  // Used to prevent concurrent calls to walletpassphrase RPC.
885  bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
886  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
887  bool EncryptWallet(const SecureString& strWalletPassphrase);
888 
889  void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
890  unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
891 
896  int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
897  DBErrors ReorderTransactions();
898 
899  void MarkDirty();
900 
907  using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
908 
909  CWalletTx* AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation& confirm, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true);
910  bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
911  void transactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) override;
912  void blockConnected(const CBlock& block, int height) override;
913  void blockDisconnected(const CBlock& block, int height) override;
914  void updatedBlockTip() override;
915  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
916 
917  struct ScanResult {
918  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
919 
925 
931  };
932  ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, Optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate);
933  void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override;
934  void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
935  void ResendWalletTransactions();
936  struct Balance {
937  CAmount m_mine_trusted{0};
938  CAmount m_mine_untrusted_pending{0};
939  CAmount m_mine_immature{0};
940  CAmount m_watchonly_trusted{0};
941  CAmount m_watchonly_untrusted_pending{0};
942  CAmount m_watchonly_immature{0};
943  };
944  Balance GetBalance(int min_depth = 0, bool avoid_reuse = true) const;
945  CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
946 
947  OutputType TransactionChangeType(const Optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend);
948 
953  bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
954  // Fetch the inputs and sign with SIGHASH_ALL.
956  // Sign the tx given the input coins and sighash.
957  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const;
958  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
959 
974  bool& complete,
975  int sighash_type = 1 /* SIGHASH_ALL */,
976  bool sign = true,
977  bool bip32derivs = true,
978  size_t* n_signed = nullptr) const;
979 
985  bool CreateTransaction(const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, const CCoinControl& coin_control, FeeCalculation& fee_calc_out, bool sign = true);
995  void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
996 
997  bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, bool use_max_sig = false) const
998  {
999  std::vector<CTxOut> v_txouts(txouts.size());
1000  std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
1001  return DummySignTx(txNew, v_txouts, use_max_sig);
1002  }
1003  bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig = false) const;
1004  bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig = false) const;
1005 
1006  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1007  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1008  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);
1009  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);
1010 
1012  unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
1013  bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
1014  bool m_signal_rbf{DEFAULT_WALLET_RBF};
1015  bool m_allow_fallback_fee{true};
1017 
1025  OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
1032  Optional<OutputType> m_default_change_type{};
1034  CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
1035 
1036  size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1037  bool TopUpKeyPool(unsigned int kpSize = 0);
1038 
1039  int64_t GetOldestKeyPoolTime() const;
1040 
1041  std::set<std::set<CTxDestination>> GetAddressGroupings() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1042  std::map<CTxDestination, CAmount> GetAddressBalances() const;
1043 
1044  std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
1045 
1050  void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1051 
1052  bool GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error);
1053  bool GetNewChangeDestination(const OutputType type, CTxDestination& dest, std::string& error);
1054 
1055  isminetype IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1056  isminetype IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1057  isminetype IsMine(const CTxIn& txin) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1062  CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
1063  isminetype IsMine(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1064  CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1065  bool IsChange(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1066  bool IsChange(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1067  CAmount GetChange(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1068  bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1070  bool IsFromMe(const CTransaction& tx) const;
1071  CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1073  bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1074  CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1075  CAmount GetChange(const CTransaction& tx) const;
1076  void chainStateFlushed(const CBlockLocator& loc) override;
1077 
1078  DBErrors LoadWallet(bool& fFirstRunRet);
1079  DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1080 
1081  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1082 
1083  bool DelAddressBook(const CTxDestination& address);
1084 
1085  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1086 
1088  void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr) override;
1089 
1091  int GetVersion() const { LOCK(cs_wallet); return nWalletVersion; }
1092 
1094  std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1095 
1097  bool HasWalletSpend(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1098 
1100  void Flush();
1101 
1103  void Close();
1104 
1106  boost::signals2::signal<void ()> NotifyUnload;
1107 
1112  boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1113  &address, const std::string &label, bool isMine,
1114  const std::string &purpose,
1116 
1121  boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1123 
1125  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1126 
1128  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1129 
1131  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
1132 
1137  boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
1138 
1140  bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1142  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1143 
1145  bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1146 
1147  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1148  bool AbandonTransaction(const uint256& hashTx);
1149 
1151  bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1152 
1153  /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1154  static std::shared_ptr<CWallet> Create(interfaces::Chain& chain, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings);
1155 
1160  void postInitProcess();
1161 
1162  bool BackupWallet(const std::string& strDest) const;
1163 
1164  /* Returns true if HD is enabled */
1165  bool IsHDEnabled() const;
1166 
1167  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
1168  bool CanGetAddresses(bool internal = false) const;
1169 
1176  void BlockUntilSyncedToCurrentChain() const EXCLUSIVE_LOCKS_REQUIRED(!::cs_main, !cs_wallet);
1177 
1179  void SetWalletFlag(uint64_t flags);
1180 
1182  void UnsetWalletFlag(uint64_t flag);
1183 
1185  bool IsWalletFlagSet(uint64_t flag) const override;
1186 
1189  bool AddWalletFlags(uint64_t flags);
1191  bool LoadWalletFlags(uint64_t flags);
1192 
1194  bool IsLegacy() const;
1195 
1197  const std::string GetDisplayName() const override {
1198  std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
1199  return strprintf("[%s]", wallet_name);
1200  };
1201 
1203  template<typename... Params>
1204  void WalletLogPrintf(std::string fmt, Params... parameters) const {
1205  LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
1206  };
1207 
1209  bool UpgradeWallet(int version, bilingual_str& error);
1210 
1212  std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
1213 
1215  std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
1216 
1218  ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
1219 
1221  ScriptPubKeyMan* GetScriptPubKeyMan(const CScript& script) const;
1223  ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
1224 
1226  std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script, SignatureData& sigdata) const;
1227 
1229  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
1230  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
1231 
1233  LegacyScriptPubKeyMan* GetLegacyScriptPubKeyMan() const;
1234  LegacyScriptPubKeyMan* GetOrCreateLegacyScriptPubKeyMan();
1235 
1237  void SetupLegacyScriptPubKeyMan();
1238 
1239  const CKeyingMaterial& GetEncryptionKey() const override;
1240  bool HasEncryptionKeys() const override;
1241 
1243  int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1244  {
1245  AssertLockHeld(cs_wallet);
1246  assert(m_last_block_processed_height >= 0);
1247  return m_last_block_processed_height;
1248  };
1249  uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1250  {
1251  AssertLockHeld(cs_wallet);
1252  assert(m_last_block_processed_height >= 0);
1253  return m_last_block_processed;
1254  }
1256  void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1257  {
1258  AssertLockHeld(cs_wallet);
1259  m_last_block_processed_height = block_height;
1260  m_last_block_processed = block_hash;
1261  };
1262 
1264  void ConnectScriptPubKeyManNotifiers();
1265 
1267  void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc);
1268 
1273  void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1274 
1279  void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1280 
1282  void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1283 
1285  DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1286 
1288  ScriptPubKeyMan* AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal);
1289 };
1290 
1295 void MaybeResendWalletTxs();
1296 
1299 {
1300 private:
1303 public:
1304  explicit WalletRescanReserver(CWallet& w) : m_wallet(w), m_could_reserve(false) {}
1305 
1306  bool reserve()
1307  {
1308  assert(!m_could_reserve);
1309  if (m_wallet.fScanningWallet.exchange(true)) {
1310  return false;
1311  }
1312  m_wallet.m_scanning_start = GetTimeMillis();
1313  m_wallet.m_scanning_progress = 0;
1314  m_could_reserve = true;
1315  return true;
1316  }
1317 
1318  bool isReserved() const
1319  {
1320  return (m_could_reserve && m_wallet.fScanningWallet);
1321  }
1322 
1324  {
1325  if (m_could_reserve) {
1326  m_wallet.fScanningWallet = false;
1327  }
1328  }
1329 };
1330 
1331 // Calculate the size of the transaction assuming all signatures are max size
1332 // Use DummySignatureCreator, which inserts 71 byte signatures everywhere.
1333 // NOTE: this requires that all inputs must be in mapWallet (eg the tx should
1334 // be IsAllFromMe).
1335 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig = false) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);
1336 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig = false);
1337 
1339 bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1340 
1342 bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1343 
1344 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:395
AmountType
Definition: wallet.h:330
constexpr CAmount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:79
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Definition: wallet.h:907
bool fChangeCached
Definition: wallet.h:340
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:762
bool IsCoinBase() const
Definition: wallet.h:550
std::atomic< bool > fScanningWallet
Definition: wallet.h:642
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:51
const uint256 & GetHash() const
Definition: wallet.h:549
std::shared_ptr< CWallet > CreateWallet(interfaces::Chain &chain, const std::string &name, Optional< bool > load_on_start, DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:247
std::unique_ptr< WalletDatabase > database
Internal database handle.
Definition: wallet.h:709
void Init()
Definition: wallet.h:351
int i
Definition: wallet.h:564
static const uint256 ONE
Definition: uint256.h:130
bool AddWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Add wallet name to persistent configuration so it will be loaded on startup.
Definition: wallet.cpp:59
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.
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we support the named feature
Definition: wallet.h:812
bool IsFeatureSupported(int wallet_version, int feature_version)
Definition: walletutil.cpp:83
static const CAmount DEFAULT_MAX_AVOIDPARTIALSPEND_FEE
maximum fee increase allowed to do partial spend avoidance, even for nodes with this feature disabled...
Definition: wallet.h:77
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:1204
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: wallet.cpp:3769
WalletDatabase & GetDatabase() const override
Definition: wallet.h:750
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:997
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:215
bool fSolvable
Whether we know how to spend this output, ignoring the lack of keys.
Definition: wallet.h:574
bool isReserved() const
Definition: wallet.h:1318
CFeeRate m_effective_feerate
Definition: wallet.h:609
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:93
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:41
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:1131
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:97
CTxDestination address
The destination.
Definition: wallet.h:159
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:728
CAmount nChangeCached
Definition: wallet.h:342
Bilingual messages:
Definition: translation.h:16
constexpr CAmount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:63
Definition: block.h:62
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:60
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:25
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
static void LogPrintf(const char *fmt, const Args &...args)
Definition: logging.h:166
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:923
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:95
TxItems wtxOrdered
Definition: wallet.h:792
const char * prefix
Definition: rest.cpp:670
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:660
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:326
bool RemoveWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Remove wallet name from persistent configuration so it will not be loaded on startup.
Definition: wallet.cpp:70
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: wallet.h:327
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:218
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:45
double ScanningProgress() const
Definition: wallet.h:859
int nWalletVersion GUARDED_BY(cs_wallet)
the current wallet version: clients below this version are not able to load the wallet ...
Definition: wallet.h:648
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:91
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:459
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:392
bool fSubtractFeeFromAmount
Definition: wallet.h:212
A version of CTransaction with the PSBT format.
Definition: psbt.h:390
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:764
int nInputBytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: wallet.h:568
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:179
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:1137
CWallet & m_wallet
Definition: wallet.h:1301
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:44
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), CFeeRate(0), CFeeRate(0), 0)
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:727
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:1243
int GetSpendSize(unsigned int out, bool use_max_sig=false) const
Definition: wallet.h:482
std::string purpose
Definition: wallet.h:193
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:325
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:89
Coin Control Features.
Definition: coincontrol.h:22
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:14
const std::string & GetLabel() const
Definition: wallet.h:201
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:1140
CWalletTx(const CWallet *wallet, CTransactionRef arg)
Definition: wallet.h:344
Access to the wallet database.
Definition: walletdb.h:177
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:306
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: wallet.cpp:148
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet, Optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:107
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:1106
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:65
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:1122
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:1142
bool isAbandoned() const
Definition: wallet.h:535
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:71
int64_t ScanningDuration() const
Definition: wallet.h:858
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in=false)
Definition: wallet.h:586
CInputCoin GetInputCoin() const
Definition: wallet.h:598
bool error(const char *fmt, const Args &...args)
Definition: system.h:52
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:123
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const std::string &name, Optional< bool > load_on_start, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:234
void Unserialize(Stream &s)
Definition: wallet.h:418
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:1091
CScript scriptPubKey
Definition: wallet.h:210
void Serialize(Stream &s) const
Definition: wallet.h:399
Mutex m_unlock_mutex
Definition: wallet.h:881
CWallet(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:769
int nDepth
Definition: wallet.h:565
Confirmation m_confirm
Definition: wallet.h:396
An input of a transaction.
Definition: transaction.h:65
bool IsNull() const
Definition: uint256.h:31
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *pwallet, bool use_max_sig=false)
Definition: wallet.cpp:1622
#define LOCK(cs)
Definition: sync.h:230
const char * name
Definition: rest.cpp:41
void SetTx(CTransactionRef arg)
Definition: wallet.h:453
AssertLockHeld(mempool.cs)
Chain notifications.
Definition: chain.h:241
bool fSafe
Whether this output is considered safe to spend.
Definition: wallet.h:584
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:787
CAmount amount
Definition: wallet.h:239
int64_t nIndex
The index of the address&#39;s key in the keypool.
Definition: wallet.h:157
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:129
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:703
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:90
std::map< std::string, std::string > StringMap
Definition: wallet.h:197
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:59
uint8_t isminefilter
Definition: wallet.h:36
WalletDatabase & GetDBHandle()
Get database handle used by this wallet.
Definition: wallet.h:746
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
Definition: wallet.h:165
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:1249
void setConflicted()
Definition: wallet.h:544
ReserveDestination & operator=(const ReserveDestination &)=delete
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:83
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:111
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:1256
An output of a transaction.
Definition: transaction.h:128
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:139
Descriptor with some wallet metadata.
Definition: walletutil.h:72
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:87
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:490
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
std::string m_label
Definition: wallet.h:191
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:308
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey&#39;ed, it will be returned to the keypool...
Definition: wallet.h:173
bool IsScanning() const
Definition: wallet.h:857
CAmount nAmount
Definition: wallet.h:211
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1298
bool isConfirmed() const
Definition: wallet.h:547
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:270
int64_t atoi64(const std::string &str)
OutputType const type
Definition: wallet.h:155
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:732
bool isConflicted() const
Definition: wallet.h:543
bool IsAbortingRescan() const
Definition: wallet.h:856
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:120
int flags
Definition: bitcoin-tx.cpp:506
bool fInMempool
Definition: wallet.h:341
void setConfirmed()
Definition: wallet.h:548
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:85
static void NotifyUnload(WalletModel *walletModel)
256-bit opaque blob.
Definition: uint256.h:124
void setUnconfirmed()
Definition: wallet.h:546
Cachable amount subdivided into watchonly and spendable parts.
Definition: ismine.h:34
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:69
static void WriteOrderPos(const int64_t &nOrderPos, mapValue_t &mapValue)
Definition: wallet.h:229
Result CommitTransaction(CWallet &wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:248
CoinSelectionParams(bool use_bnb, size_t change_output_size, size_t change_spend_size, CFeeRate effective_feerate, CFeeRate long_term_feerate, CFeeRate discard_feerate, size_t tx_noinputs_size)
Definition: wallet.h:616
bool IsChange() const
Definition: wallet.h:200
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:1115
MasterKeyMap mapMasterKeys
Definition: wallet.h:765
int vout
Definition: wallet.h:240
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:83
CFeeRate m_discard_feerate
Definition: wallet.h:611
Address book data.
Definition: wallet.h:187
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
StringMap destdata
Definition: wallet.h:198
CTxDestination destination
Definition: wallet.h:238
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:319
void Reset()
Definition: ismine.h:39
bool IsInMainChain() const
Definition: wallet.h:527
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:21
void Unserialize(Stream &s)
Definition: wallet.h:252
const CWalletTx * tx
Definition: wallet.h:563
void SetLabel(const std::string &label)
Definition: wallet.h:202
bool GetReservedDestination(CTxDestination &pubkey, bool internal)
Reserve an address.
Definition: wallet.cpp:3525
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:633
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:2113
A wrapper to reserve an address from a wallet.
Definition: wallet.h:148
void AbortRescan()
Definition: wallet.h:855
Definition: wallet.h:236
#define GUARDED_BY(x)
Definition: threadsafety.h:38
RecursiveMutex cs_wallet
Definition: wallet.h:741
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:1125
bool fInternal
Whether this is from the internal (change output) keypool.
Definition: wallet.h:161
Optional< int > last_scanned_height
Definition: wallet.h:924
A mutable version of CTransaction.
Definition: transaction.h:353
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:930
void FundTransaction(CWallet *const pwallet, CMutableTransaction &tx, CAmount &fee_out, int &change_position, const UniValue &options, CCoinControl &coinControl, bool override_min_fee)
Definition: rpcwallet.cpp:3059
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:81
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:864
static std::vector< COutput > vCoins
std::atomic< int64_t > m_scanning_start
Definition: wallet.h:643
unsigned int nTimeReceived
time received by this node
Definition: wallet.h:309
std::string m_name
Wallet name: relative directory name or "" for default wallet.
Definition: wallet.h:706
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
Confirmation(Status s=UNCONFIRMED, int b=0, uint256 h=uint256(), int i=0)
Definition: wallet.h:393
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:214
std::atomic< double > m_scanning_progress
Definition: wallet.h:644
ChangeType
General change type (added, updated, removed).
Definition: ui_change_type.h:9
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:62
const std::string GetDisplayName() const override
Returns a bracketed wallet name for displaying in logs, will return [default wallet] if the wallet ha...
Definition: wallet.h:1197
DatabaseStatus
Definition: db.h:213
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:1128
CFeeRate m_long_term_feerate
Definition: wallet.h:610
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:791
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:152
WalletRescanReserver(CWallet &w)
Definition: wallet.h:1304
static const CAmount DEFAULT_DISCARD_FEE
-discardfee default
Definition: wallet.h:67
CTransactionRef tx
Definition: wallet.h:366
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig=false) EXCLUSIVE_LOCKS_REQUIRED(wallet-> cs_wallet)
Definition: wallet.cpp:1597
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: wallet.cpp:133
Legacy class used for deserializing vtxPrev for backwards compatibility.
Definition: wallet.h:248
const CWallet *const pwallet
Definition: wallet.h:273
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:113
~CWallet()
Definition: wallet.h:776
void KeepDestination()
Keep the address. Do not return it&#39;s key to the keypool when this object goes out of scope...
Definition: wallet.cpp:3547
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:95
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:307
void ReturnDestination()
Return reserved address.
Definition: wallet.cpp:3556
ScriptPubKeyMan * m_spk_man
The ScriptPubKeyMan to reserve from. Based on type when GetReservedDestination is called...
Definition: wallet.h:154
An instance of this class represents one database.
Definition: db.h:104
bool isUnconfirmed() const
Definition: wallet.h:545
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:100