Bitcoin Core  0.19.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 <tinyformat.h>
15 #include <ui_interface.h>
16 #include <util/strencodings.h>
17 #include <util/system.h>
18 #include <validationinterface.h>
19 #include <wallet/coinselection.h>
20 #include <wallet/crypter.h>
21 #include <wallet/scriptpubkeyman.h>
22 #include <wallet/walletdb.h>
23 #include <wallet/walletutil.h>
24 
25 #include <algorithm>
26 #include <atomic>
27 #include <map>
28 #include <memory>
29 #include <set>
30 #include <stdexcept>
31 #include <stdint.h>
32 #include <string>
33 #include <utility>
34 #include <vector>
35 
36 #include <boost/signals2/signal.hpp>
37 
38 using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
39 
45 void UnloadWallet(std::shared_ptr<CWallet>&& wallet);
46 
47 bool AddWallet(const std::shared_ptr<CWallet>& wallet);
48 bool RemoveWallet(const std::shared_ptr<CWallet>& wallet);
49 bool HasWallets();
50 std::vector<std::shared_ptr<CWallet>> GetWallets();
51 std::shared_ptr<CWallet> GetWallet(const std::string& name);
52 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const WalletLocation& location, std::string& error, std::vector<std::string>& warnings);
53 std::unique_ptr<interfaces::Handler> HandleLoadWallet(LoadWalletFn load_wallet);
54 
56  SUCCESS,
59 };
60 
61 WalletCreationStatus CreateWallet(interfaces::Chain& chain, const SecureString& passphrase, uint64_t wallet_creation_flags, const std::string& name, std::string& error, std::vector<std::string>& warnings, std::shared_ptr<CWallet>& result);
62 
66 static const CAmount DEFAULT_FALLBACK_FEE = 0;
68 static const CAmount DEFAULT_DISCARD_FEE = 10000;
70 static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
74 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
76 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS = false;
78 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
80 static const bool DEFAULT_WALLET_RBF = false;
81 static const bool DEFAULT_WALLETBROADCAST = true;
82 static const bool DEFAULT_DISABLE_WALLET = false;
86 constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
89 
91 static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
92 
93 class CCoinControl;
94 class COutput;
95 class CScript;
96 class CWalletTx;
97 struct FeeCalculation;
98 enum class FeeEstimateMode;
99 class ReserveDestination;
100 
103 
106 
107 static constexpr uint64_t KNOWN_WALLET_FLAGS =
112 
113 static constexpr uint64_t MUTABLE_WALLET_FLAGS =
115 
116 static const std::map<std::string,WalletFlags> WALLET_FLAG_MAP{
117  {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
118  {"blank", WALLET_FLAG_BLANK_WALLET},
119  {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
120  {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
121 };
122 
123 extern const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS;
124 
141 {
142 protected:
144  CWallet* const pwallet;
146  ScriptPubKeyMan* m_spk_man{nullptr};
149  int64_t nIndex{-1};
153  bool fInternal{false};
154 
155 public:
157  explicit ReserveDestination(CWallet* pwallet, OutputType type)
158  : pwallet(pwallet)
159  , type(type) { }
160 
161  ReserveDestination(const ReserveDestination&) = delete;
162  ReserveDestination& operator=(const ReserveDestination&) = delete;
163 
166  {
167  ReturnDestination();
168  }
169 
171  bool GetReservedDestination(CTxDestination& pubkey, bool internal);
173  void ReturnDestination();
175  void KeepDestination();
176 };
177 
180 {
181 public:
182  std::string name;
183  std::string purpose;
184 
185  CAddressBookData() : purpose("unknown") {}
186 
187  typedef std::map<std::string, std::string> StringMap;
188  StringMap destdata;
189 };
190 
192 {
196 };
197 
198 typedef std::map<std::string, std::string> mapValue_t;
199 
200 
201 static inline void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
202 {
203  if (!mapValue.count("n"))
204  {
205  nOrderPos = -1; // TODO: calculate elsewhere
206  return;
207  }
208  nOrderPos = atoi64(mapValue["n"].c_str());
209 }
210 
211 
212 static inline void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
213 {
214  if (nOrderPos == -1)
215  return;
216  mapValue["n"] = i64tostr(nOrderPos);
217 }
218 
220 {
223  int vout;
224 };
225 
232 {
233 public:
234  template<typename Stream>
235  void Unserialize(Stream& s)
236  {
237  CTransactionRef tx;
238  uint256 hashBlock;
239  std::vector<uint256> vMerkleBranch;
240  int nIndex;
241 
242  s >> tx >> hashBlock >> vMerkleBranch >> nIndex;
243  }
244 };
245 
246 //Get the marginal bytes of spending the specified output
247 int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, bool use_max_sig = false);
248 
254 {
255 private:
256  const CWallet* pwallet;
257 
261  static const uint256 ABANDON_HASH;
262 
263 public:
290  std::vector<std::pair<std::string, std::string> > vOrderForm;
291  unsigned int fTimeReceivedIsTxTime;
292  unsigned int nTimeReceived;
293 
302  unsigned int nTimeSmart;
308  bool fFromMe;
309  int64_t nOrderPos;
310  std::multimap<int64_t, CWalletTx*>::const_iterator m_it_wtxOrdered;
311 
312  // memory only
313  enum AmountType { DEBIT, CREDIT, IMMATURE_CREDIT, AVAILABLE_CREDIT, AMOUNTTYPE_ENUM_ELEMENTS };
314  CAmount GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate = false) const;
315  mutable CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS];
322  mutable bool m_is_cache_empty{true};
323  mutable bool fChangeCached;
324  mutable bool fInMempool;
326 
327  CWalletTx(const CWallet* pwalletIn, CTransactionRef arg)
328  : tx(std::move(arg))
329  {
330  Init(pwalletIn);
331  }
332 
333  void Init(const CWallet* pwalletIn)
334  {
335  pwallet = pwalletIn;
336  mapValue.clear();
337  vOrderForm.clear();
338  fTimeReceivedIsTxTime = false;
339  nTimeReceived = 0;
340  nTimeSmart = 0;
341  fFromMe = false;
342  fChangeCached = false;
343  fInMempool = false;
344  nChangeCached = 0;
345  nOrderPos = -1;
346  m_confirm = Confirmation{};
347  }
348 
350 
351  /* New transactions start as UNCONFIRMED. At BlockConnected,
352  * they will transition to CONFIRMED. In case of reorg, at BlockDisconnected,
353  * they roll back to UNCONFIRMED. If we detect a conflicting transaction at
354  * block connection, we update conflicted tx and its dependencies as CONFLICTED.
355  * If tx isn't confirmed and outside of mempool, the user may switch it to ABANDONED
356  * by using the abandontransaction call. This last status may be override by a CONFLICTED
357  * or CONFIRMED transition.
358  */
359  enum Status {
363  ABANDONED
364  };
365 
366  /* Confirmation includes tx status and a triplet of {block height/block hash/tx index in block}
367  * at which tx has been confirmed. All three are set to 0 if tx is unconfirmed or abandoned.
368  * Meaning of these fields changes with CONFLICTED state where they instead point to block hash
369  * and block height of the deepest conflicting tx.
370  */
371  struct Confirmation {
375  int nIndex;
376  Confirmation(Status s = UNCONFIRMED, int b = 0, uint256 h = uint256(), int i = 0) : status(s), block_height(b), hashBlock(h), nIndex(i) {}
377  };
378 
380 
381  template<typename Stream>
382  void Serialize(Stream& s) const
383  {
384  mapValue_t mapValueCopy = mapValue;
385 
386  mapValueCopy["fromaccount"] = "";
387  WriteOrderPos(nOrderPos, mapValueCopy);
388  if (nTimeSmart) {
389  mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);
390  }
391 
392  std::vector<char> dummy_vector1;
393  std::vector<char> dummy_vector2;
394  bool dummy_bool = false;
395  uint256 serializedHash = isAbandoned() ? ABANDON_HASH : m_confirm.hashBlock;
396  int serializedIndex = isAbandoned() || isConflicted() ? -1 : m_confirm.nIndex;
397  s << tx << serializedHash << dummy_vector1 << serializedIndex << dummy_vector2 << mapValueCopy << vOrderForm << fTimeReceivedIsTxTime << nTimeReceived << fFromMe << dummy_bool;
398  }
399 
400  template<typename Stream>
401  void Unserialize(Stream& s)
402  {
403  Init(nullptr);
404 
405  std::vector<uint256> dummy_vector1;
406  std::vector<CMerkleTx> dummy_vector2;
407  bool dummy_bool;
408  int serializedIndex;
409  s >> tx >> m_confirm.hashBlock >> dummy_vector1 >> serializedIndex >> dummy_vector2 >> mapValue >> vOrderForm >> fTimeReceivedIsTxTime >> nTimeReceived >> fFromMe >> dummy_bool;
410 
411  /* At serialization/deserialization, an nIndex == -1 means that hashBlock refers to
412  * the earliest block in the chain we know this or any in-wallet ancestor conflicts
413  * with. If nIndex == -1 and hashBlock is ABANDON_HASH, it means transaction is abandoned.
414  * In same context, an nIndex >= 0 refers to a confirmed transaction (if hashBlock set) or
415  * unconfirmed one. Older clients interpret nIndex == -1 as unconfirmed for backward
416  * compatibility (pre-commit 9ac63d6).
417  */
418  if (serializedIndex == -1 && m_confirm.hashBlock == ABANDON_HASH) {
419  setAbandoned();
420  } else if (serializedIndex == -1) {
421  setConflicted();
422  } else if (!m_confirm.hashBlock.IsNull()) {
423  m_confirm.nIndex = serializedIndex;
424  setConfirmed();
425  }
426 
427  ReadOrderPos(nOrderPos, mapValue);
428  nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
429 
430  mapValue.erase("fromaccount");
431  mapValue.erase("spent");
432  mapValue.erase("n");
433  mapValue.erase("timesmart");
434  }
435 
437  {
438  tx = std::move(arg);
439  }
440 
442  void MarkDirty()
443  {
444  m_amounts[DEBIT].Reset();
445  m_amounts[CREDIT].Reset();
446  m_amounts[IMMATURE_CREDIT].Reset();
447  m_amounts[AVAILABLE_CREDIT].Reset();
448  fChangeCached = false;
449  m_is_cache_empty = true;
450  }
451 
452  void BindWallet(CWallet *pwalletIn)
453  {
454  pwallet = pwalletIn;
455  MarkDirty();
456  }
457 
459  CAmount GetDebit(const isminefilter& filter) const;
460  CAmount GetCredit(const isminefilter& filter) const;
461  CAmount GetImmatureCredit(bool fUseCache = true) const;
462  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
463  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The
464  // annotation "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid
465  // having to resolve the issue of member access into incomplete type CWallet.
466  CAmount GetAvailableCredit(bool fUseCache = true, const isminefilter& filter = ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS;
467  CAmount GetImmatureWatchOnlyCredit(const bool fUseCache = true) const;
468  CAmount GetChange() const;
469 
470  // Get the marginal bytes if spending the specified output from this transaction
471  int GetSpendSize(unsigned int out, bool use_max_sig = false) const
472  {
473  return CalculateMaximumSignedInputSize(tx->vout[out], pwallet, use_max_sig);
474  }
475 
476  void GetAmounts(std::list<COutputEntry>& listReceived,
477  std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const;
478 
479  bool IsFromMe(const isminefilter& filter) const
480  {
481  return (GetDebit(filter) > 0);
482  }
483 
484  // True if only scriptSigs are different
485  bool IsEquivalentTo(const CWalletTx& tx) const;
486 
487  bool InMempool() const;
488  bool IsTrusted(interfaces::Chain::Lock& locked_chain) const;
489  bool IsTrusted(interfaces::Chain::Lock& locked_chain, std::set<uint256>& trusted_parents) const;
490 
491  int64_t GetTxTime() const;
492 
493  // Pass this transaction to node for mempool insertion and relay to peers if flag set to true
494  bool SubmitMemoryPoolAndRelay(std::string& err_string, bool relay);
495 
496  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
497  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
498  // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
499  // resolve the issue of member access into incomplete type CWallet. Note
500  // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
501  // in place.
502  std::set<uint256> GetConflicts() const NO_THREAD_SAFETY_ANALYSIS;
503 
510  // TODO: Remove "NO_THREAD_SAFETY_ANALYSIS" and replace it with the correct
511  // annotation "EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)". The annotation
512  // "NO_THREAD_SAFETY_ANALYSIS" was temporarily added to avoid having to
513  // resolve the issue of member access into incomplete type CWallet. Note
514  // that we still have the runtime check "AssertLockHeld(pwallet->cs_wallet)"
515  // in place.
516  int GetDepthInMainChain() const NO_THREAD_SAFETY_ANALYSIS;
517  bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
518 
524  int GetBlocksToMaturity() const;
525  bool isAbandoned() const { return m_confirm.status == CWalletTx::ABANDONED; }
527  {
528  m_confirm.status = CWalletTx::ABANDONED;
529  m_confirm.hashBlock = uint256();
530  m_confirm.block_height = 0;
531  m_confirm.nIndex = 0;
532  }
533  bool isConflicted() const { return m_confirm.status == CWalletTx::CONFLICTED; }
535  bool isUnconfirmed() const { return m_confirm.status == CWalletTx::UNCONFIRMED; }
537  bool isConfirmed() const { return m_confirm.status == CWalletTx::CONFIRMED; }
538  void setConfirmed() { m_confirm.status = CWalletTx::CONFIRMED; }
539  const uint256& GetHash() const { return tx->GetHash(); }
540  bool IsCoinBase() const { return tx->IsCoinBase(); }
541  bool IsImmatureCoinBase() const;
542 };
543 
544 class COutput
545 {
546 public:
547  const CWalletTx *tx;
548  int i;
549  int nDepth;
550 
553 
556 
558  bool fSolvable;
559 
562 
568  bool fSafe;
569 
570  COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in = false)
571  {
572  tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; fSafe = fSafeIn; nInputBytes = -1; use_max_sig = use_max_sig_in;
573  // If known and signable by the given wallet, compute nInputBytes
574  // Failure will keep this value -1
575  if (fSpendable && tx) {
576  nInputBytes = tx->GetSpendSize(i, use_max_sig);
577  }
578  }
579 
580  std::string ToString() const;
581 
582  inline CInputCoin GetInputCoin() const
583  {
584  return CInputCoin(tx->tx, i, nInputBytes);
585  }
586 };
587 
589 {
590  bool use_bnb = true;
591  size_t change_output_size = 0;
592  size_t change_spend_size = 0;
593  CFeeRate effective_fee = CFeeRate(0);
594  size_t tx_noinputs_size = 0;
596  bool m_subtract_fee_outputs = false;
597 
598  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) {}
600 };
601 
602 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
607 {
608 private:
609  CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
610 
611 
612  bool Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys = false);
613 
614  std::atomic<bool> fAbortRescan{false};
615  std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
616  std::atomic<int64_t> m_scanning_start{0};
617  std::atomic<double> m_scanning_progress{0};
618  std::mutex mutexScanning;
619  friend class WalletRescanReserver;
620 
622  int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
623 
625  int nWalletMaxVersion GUARDED_BY(cs_wallet) = FEATURE_BASE;
626 
627  int64_t nNextResend = 0;
628  int64_t nLastResend = 0;
629  bool fBroadcastTransactions = false;
630  // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
631  std::atomic<int64_t> m_best_block_time {0};
632 
638  typedef std::multimap<COutPoint, uint256> TxSpends;
639  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
640  void AddToSpends(const COutPoint& outpoint, const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
641  void AddToSpends(const uint256& wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
642 
656  bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
657 
658  /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
659  void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
660 
661  /* Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed */
662  void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
663 
664  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
665 
666  /* Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
667  * Should be called with non-zero block_hash and posInBlock if this is for a transaction that is included in a block. */
668  void SyncTransaction(const CTransactionRef& tx, CWalletTx::Confirmation confirm, bool update_tx = true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
669 
670  std::atomic<uint64_t> m_wallet_flags{0};
671 
672  bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose);
673 
675  void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
676 
678  void UnsetBlankWalletFlag(WalletBatch& batch) override;
679 
682 
685 
687  std::unique_ptr<WalletDatabase> database;
688 
696  uint256 m_last_block_processed GUARDED_BY(cs_wallet);
697 
698  /* Height of last block processed is used by wallet to know depth of transactions
699  * without relying on Chain interface beyond asynchronous updates. For safety, we
700  * initialize it to -1. Height is a pointer on node's tip and doesn't imply
701  * that the wallet has scanned sequentially all blocks up to this one.
702  */
703  int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
704 
705  std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
706  std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
707 
708  // Indexed by a unique identifier produced by each ScriptPubKeyMan using
709  // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
710  std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
711 
712 public:
713  /*
714  * Main wallet lock.
715  * This lock protects all the fields added by CWallet.
716  */
718 
723  {
724  return *database;
725  }
726  WalletDatabase& GetDatabase() override { return *database; }
727 
733  bool SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet,
734  const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
735 
736  const WalletLocation& GetLocation() const { return m_location; }
737 
740  const std::string& GetName() const { return m_location.GetName(); }
741 
742  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
743  MasterKeyMap mapMasterKeys;
744  unsigned int nMasterKeyMaxID = 0;
745 
747  CWallet(interfaces::Chain* chain, const WalletLocation& location, std::unique_ptr<WalletDatabase> database)
748  : m_chain(chain),
749  m_location(location),
750  database(std::move(database))
751  {
752  }
753 
755  {
756  // Should not have slots connected at this point.
757  assert(NotifyUnload.empty());
758  }
759 
760  bool IsCrypted() const;
761  bool IsLocked() const override;
762  bool Lock();
763 
765  std::unique_ptr<interfaces::Chain::Lock> LockChain() { return m_chain ? m_chain->lock() : nullptr; }
766 
767  std::map<uint256, CWalletTx> mapWallet GUARDED_BY(cs_wallet);
768 
769  typedef std::multimap<int64_t, CWalletTx*> TxItems;
770  TxItems wtxOrdered;
771 
772  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
773  uint64_t nAccountingEntryNumber = 0;
774 
775  std::map<CTxDestination, CAddressBookData> mapAddressBook GUARDED_BY(cs_wallet);
776 
777  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
778 
780  std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
781 
783  void handleNotifications();
784 
786  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
787 
788  const CWalletTx* GetWalletTx(const uint256& hash) const;
789 
791  bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
792 
796  void AvailableCoins(interfaces::Chain::Lock& locked_chain, 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);
797 
801  std::map<CTxDestination, std::vector<COutput>> ListCoins(interfaces::Chain::Lock& locked_chain) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
802 
806  const CTxOut& FindNonChangeParentOutput(const CTransaction& tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
807 
814  bool SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
815  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const;
816 
817  bool IsSpent(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
818 
819  // Whether this or any known UTXO with the same single key has been spent.
820  bool IsSpentKey(const uint256& hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
821  void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
822 
823  std::vector<OutputGroup> GroupOutputs(const std::vector<COutput>& outputs, bool single_coin) const;
824 
825  bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
826  void LockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
827  void UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
828  void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
829  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
830 
831  /*
832  * Rescan abort properties
833  */
834  void AbortRescan() { fAbortRescan = true; }
835  bool IsAbortingRescan() { return fAbortRescan; }
836  bool IsScanning() { return fScanningWallet; }
837  int64_t ScanningDuration() const { return fScanningWallet ? GetTimeMillis() - m_scanning_start : 0; }
838  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
839 
841  void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
842 
843  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
844 
846  bool AddDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
848  bool EraseDestData(WalletBatch& batch, const CTxDestination& dest, const std::string& key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
850  void LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
852  bool GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
854  std::vector<std::string> GetDestValues(const std::string& prefix) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
855 
857  int64_t nRelockTime = 0;
858 
859  bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
860  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
861  bool EncryptWallet(const SecureString& strWalletPassphrase);
862 
863  void GetKeyBirthTimes(interfaces::Chain::Lock& locked_chain, std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
864  unsigned int ComputeTimeSmart(const CWalletTx& wtx) const;
865 
870  int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
871  DBErrors ReorderTransactions();
872 
873  void MarkDirty();
874  bool AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose=true);
875  void LoadToWallet(CWalletTx& wtxIn) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
876  void TransactionAddedToMempool(const CTransactionRef& tx) override;
877  void BlockConnected(const CBlock& block, const std::vector<CTransactionRef>& vtxConflicted, int height) override;
878  void BlockDisconnected(const CBlock& block, int height) override;
879  void UpdatedBlockTip() override;
880  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
881 
882  struct ScanResult {
883  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
884 
890 
896  };
897  ScanResult ScanForWalletTransactions(const uint256& first_block, const uint256& last_block, const WalletRescanReserver& reserver, bool fUpdate);
898  void TransactionRemovedFromMempool(const CTransactionRef &ptx) override;
899  void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
900  void ResendWalletTransactions();
901  struct Balance {
902  CAmount m_mine_trusted{0};
903  CAmount m_mine_untrusted_pending{0};
904  CAmount m_mine_immature{0};
905  CAmount m_watchonly_trusted{0};
906  CAmount m_watchonly_untrusted_pending{0};
907  CAmount m_watchonly_immature{0};
908  };
909  Balance GetBalance(int min_depth = 0, bool avoid_reuse = true) const;
910  CAmount GetAvailableBalance(const CCoinControl* coinControl = nullptr) const;
911 
912  OutputType TransactionChangeType(OutputType change_type, const std::vector<CRecipient>& vecSend);
913 
918  bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
920 
926  bool CreateTransaction(interfaces::Chain::Lock& locked_chain, const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CAmount& nFeeRet, int& nChangePosInOut,
927  std::string& strFailReason, const CCoinControl& coin_control, bool sign = true);
937  void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
938 
939  bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, bool use_max_sig = false) const
940  {
941  std::vector<CTxOut> v_txouts(txouts.size());
942  std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
943  return DummySignTx(txNew, v_txouts, use_max_sig);
944  }
945  bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig = false) const;
946  bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig = false) const;
947 
948  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
949  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
950  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);
951  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);
952 
954  unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
955  bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
956  bool m_signal_rbf{DEFAULT_WALLET_RBF};
957  bool m_allow_fallback_fee{true};
959 
965  CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
966  OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
967  OutputType m_default_change_type{DEFAULT_CHANGE_TYPE};
969  CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
970 
971  size_t KeypoolCountExternalKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
972  bool TopUpKeyPool(unsigned int kpSize = 0);
973 
974  int64_t GetOldestKeyPoolTime();
975 
976  std::set<std::set<CTxDestination>> GetAddressGroupings() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
977  std::map<CTxDestination, CAmount> GetAddressBalances(interfaces::Chain::Lock& locked_chain);
978 
979  std::set<CTxDestination> GetLabelAddresses(const std::string& label) const;
980 
985  void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
986 
987  bool GetNewDestination(const OutputType type, const std::string label, CTxDestination& dest, std::string& error);
988  bool GetNewChangeDestination(const OutputType type, CTxDestination& dest, std::string& error);
989 
990  isminetype IsMine(const CTxDestination& dest) const;
991  isminetype IsMine(const CScript& script) const;
992  isminetype IsMine(const CTxIn& txin) const;
997  CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
998  isminetype IsMine(const CTxOut& txout) const;
999  CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
1000  bool IsChange(const CTxOut& txout) const;
1001  bool IsChange(const CScript& script) const;
1002  CAmount GetChange(const CTxOut& txout) const;
1003  bool IsMine(const CTransaction& tx) const;
1005  bool IsFromMe(const CTransaction& tx) const;
1006  CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
1008  bool IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const;
1009  CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
1010  CAmount GetChange(const CTransaction& tx) const;
1011  void ChainStateFlushed(const CBlockLocator& loc) override;
1012 
1013  DBErrors LoadWallet(bool& fFirstRunRet);
1014  DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
1015  DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1016 
1017  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
1018 
1019  bool DelAddressBook(const CTxDestination& address);
1020 
1021  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1022 
1024  void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr, bool fExplicit = false) override;
1025 
1027  bool SetMaxVersion(int nVersion);
1028 
1030  int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
1031 
1033  std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1034 
1036  bool HasWalletSpend(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1037 
1039  void Flush(bool shutdown=false);
1040 
1042  boost::signals2::signal<void ()> NotifyUnload;
1043 
1048  boost::signals2::signal<void (CWallet *wallet, const CTxDestination
1049  &address, const std::string &label, bool isMine,
1050  const std::string &purpose,
1052 
1057  boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
1059 
1061  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
1062 
1064  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
1065 
1067  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
1068 
1073  boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
1074 
1076  bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
1078  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
1079 
1081  bool TransactionCanBeAbandoned(const uint256& hashTx) const;
1082 
1083  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1084  bool AbandonTransaction(const uint256& hashTx);
1085 
1087  bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
1088 
1090  static bool Verify(interfaces::Chain& chain, const WalletLocation& location, bool salvage_wallet, std::string& error_string, std::vector<std::string>& warnings);
1091 
1092  /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1093  static std::shared_ptr<CWallet> CreateWalletFromFile(interfaces::Chain& chain, const WalletLocation& location, std::string& error, std::vector<std::string>& warnings, uint64_t wallet_creation_flags = 0);
1094 
1099  void postInitProcess();
1100 
1101  bool BackupWallet(const std::string& strDest);
1102 
1103  /* Returns true if HD is enabled */
1104  bool IsHDEnabled() const;
1105 
1106  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
1107  bool CanGetAddresses(bool internal = false);
1108 
1115  void BlockUntilSyncedToCurrentChain() LOCKS_EXCLUDED(cs_main, cs_wallet);
1116 
1118  void SetWalletFlag(uint64_t flags);
1119 
1121  void UnsetWalletFlag(uint64_t flag);
1122 
1124  bool IsWalletFlagSet(uint64_t flag) const override;
1125 
1128  bool SetWalletFlags(uint64_t overwriteFlags, bool memOnly);
1129 
1131  const std::string GetDisplayName() const override {
1132  std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
1133  return strprintf("[%s]", wallet_name);
1134  };
1135 
1137  template<typename... Params>
1138  void WalletLogPrintf(std::string fmt, Params... parameters) const {
1139  LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
1140  };
1141 
1143  std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
1144 
1146  std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
1147 
1149  ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
1150 
1152  ScriptPubKeyMan* GetScriptPubKeyMan(const CScript& script) const;
1154  ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
1155 
1157  std::unique_ptr<SigningProvider> GetSigningProvider(const CScript& script) const;
1158  std::unique_ptr<SigningProvider> GetSigningProvider(const CScript& script, SignatureData& sigdata) const;
1159 
1161  LegacyScriptPubKeyMan* GetLegacyScriptPubKeyMan() const;
1162  LegacyScriptPubKeyMan* GetOrCreateLegacyScriptPubKeyMan();
1163 
1165  void SetupLegacyScriptPubKeyMan();
1166 
1167  const CKeyingMaterial& GetEncryptionKey() const override;
1168  bool HasEncryptionKeys() const override;
1169 
1171  int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1172  {
1173  AssertLockHeld(cs_wallet);
1174  assert(m_last_block_processed_height >= 0);
1175  return m_last_block_processed_height;
1176  };
1178  void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
1179  {
1180  AssertLockHeld(cs_wallet);
1181  m_last_block_processed_height = block_height;
1182  m_last_block_processed = block_hash;
1183  };
1184 
1186  void ConnectScriptPubKeyManNotifiers();
1187 };
1188 
1193 void MaybeResendWalletTxs();
1194 
1197 {
1198 private:
1201 public:
1202  explicit WalletRescanReserver(CWallet* w) : m_wallet(w), m_could_reserve(false) {}
1203 
1204  bool reserve()
1205  {
1206  assert(!m_could_reserve);
1207  std::lock_guard<std::mutex> lock(m_wallet->mutexScanning);
1208  if (m_wallet->fScanningWallet) {
1209  return false;
1210  }
1211  m_wallet->m_scanning_start = GetTimeMillis();
1212  m_wallet->m_scanning_progress = 0;
1213  m_wallet->fScanningWallet = true;
1214  m_could_reserve = true;
1215  return true;
1216  }
1217 
1218  bool isReserved() const
1219  {
1220  return (m_could_reserve && m_wallet->fScanningWallet);
1221  }
1222 
1224  {
1225  std::lock_guard<std::mutex> lock(m_wallet->mutexScanning);
1226  if (m_could_reserve) {
1227  m_wallet->fScanningWallet = false;
1228  }
1229  }
1230 };
1231 
1232 // Calculate the size of the transaction assuming all signatures are max size
1233 // Use DummySignatureCreator, which inserts 71 byte signatures everywhere.
1234 // NOTE: this requires that all inputs must be in mapWallet (eg the tx should
1235 // be IsAllFromMe).
1236 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig = false) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);
1237 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig = false);
1238 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:408
AmountType
Definition: wallet.h:313
bool fChangeCached
Definition: wallet.h:323
const CWallet * pwallet
Definition: wallet.h:256
std::atomic< bool > fScanningWallet
Definition: wallet.h:615
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:53
std::unique_ptr< WalletDatabase > database
Internal database handle.
Definition: wallet.h:687
int i
Definition: wallet.h:548
void BindWallet(CWallet *pwalletIn)
Definition: wallet.h:452
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::unique_ptr< interfaces::Handler > m_chain_notifications_handler
Registered interfaces::Chain::Notifications handler.
Definition: wallet.h:780
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:198
bool fSolvable
Whether we know how to spend this output, ignoring the lack of keys.
Definition: wallet.h:558
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:84
bool isConfirmed() const
Definition: wallet.h:537
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:126
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:1067
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:88
CTxDestination address
The destination.
Definition: wallet.h:151
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:706
CAmount nChangeCached
Definition: wallet.h:325
Result CommitTransaction(CWallet &wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< std::string > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:375
constexpr CAmount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:64
Definition: block.h:72
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:54
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
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:479
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:939
constexpr OutputType DEFAULT_CHANGE_TYPE
Default for -changetype.
Definition: wallet.h:105
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:888
void setAbandoned()
Definition: wallet.h:526
bool use_max_sig
Whether to use the maximum sized, 72 byte signature when calculating the size of the input spend...
Definition: wallet.h:561
static const CAmount COIN
Definition: amount.h:14
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:53
FeeEstimateMode
Definition: fees.h:49
TxItems wtxOrdered
Definition: wallet.h:770
const char * prefix
Definition: rest.cpp:650
CWallet(interfaces::Chain *chain, const WalletLocation &location, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:747
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:638
Interface for querying locked chain state, used by legacy code that assumes state won&#39;t change betwee...
Definition: chain.h:64
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:309
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: wallet.h:310
bool isConflicted() const
Definition: wallet.h:533
An instance of this class represents one database.
Definition: db.h:111
bool IsInMainChain() const
Definition: wallet.h:517
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:67
static void ReadOrderPos(int64_t &nOrderPos, mapValue_t &mapValue)
Definition: wallet.h:201
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:163
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:39
int nWalletVersion GUARDED_BY(cs_wallet)
the current wallet version: clients below this version are not able to load the wallet ...
Definition: wallet.h:622
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:82
std::unique_ptr< interfaces::Chain::Lock > LockChain()
Interface to assert chain access and if successful lock it.
Definition: wallet.h:765
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:442
bool fSubtractFeeFromAmount
Definition: wallet.h:195
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:742
std::string name
Definition: wallet.h:182
int nInputBytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: wallet.h:552
bool IsCoinBase() const
Definition: wallet.h:540
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:128
int64_t ScanningDuration() const
Definition: wallet.h:837
WalletCreationStatus
Definition: wallet.h:55
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:1073
bool isUnconfirmed() const
Definition: wallet.h:535
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:45
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:705
bool fSpendable
Whether we have the private keys to spend this output.
Definition: wallet.h:555
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:1171
bool IsNull() const
Definition: uint256.h:30
std::string purpose
Definition: wallet.h:183
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:308
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:80
Coin Control Features.
Definition: coincontrol.h:22
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:13
double ScanningProgress() const
Definition: wallet.h:838
WalletDatabase & GetDatabase() override
Definition: wallet.h:726
Access to the wallet database.
Definition: walletdb.h:175
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:289
std::mutex mutexScanning
Definition: wallet.h:618
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: dummywallet.cpp:86
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:786
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:1042
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:66
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:1058
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:1078
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in=false)
Definition: wallet.h:570
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:116
void Unserialize(Stream &s)
Definition: wallet.h:401
CScript scriptPubKey
Definition: wallet.h:193
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned, only used at serialization/deserializat...
Definition: wallet.h:261
int nDepth
Definition: wallet.h:549
const std::string & GetName() const
Get wallet name.
Definition: walletutil.h:77
Confirmation m_confirm
Definition: wallet.h:379
ChangeType
General change type (added, updated, removed).
Definition: ui_interface.h:21
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:1138
Chain & m_chain
Definition: chain.cpp:190
An input of a transaction.
Definition: transaction.h:63
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *pwallet, bool use_max_sig=false)
Definition: wallet.cpp:1518
#define LOCK(cs)
Definition: sync.h:179
const char * name
Definition: rest.cpp:40
void SetTx(CTransactionRef arg)
Definition: wallet.h:436
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:1030
WalletCreationStatus CreateWallet(interfaces::Chain &chain, const SecureString &passphrase, uint64_t wallet_creation_flags, const std::string &name, std::string &error, std::vector< std::string > &warnings, std::shared_ptr< CWallet > &result)
Definition: dummywallet.cpp:80
Chain notifications.
Definition: chain.h:216
bool fSafe
Whether this output is considered safe to spend.
Definition: wallet.h:568
CAmount amount
Definition: wallet.h:222
std::string i64tostr(int64_t n)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:106
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:681
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:81
std::map< std::string, std::string > StringMap
Definition: wallet.h:187
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:57
uint8_t isminefilter
Definition: wallet.h:29
WalletDatabase & GetDBHandle()
Get database handle used by this wallet.
Definition: wallet.h:722
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
Definition: wallet.h:157
void setConflicted()
Definition: wallet.h:534
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:74
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:102
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:1178
An output of a transaction.
Definition: transaction.h:133
const WalletLocation & GetLocation() const
Definition: wallet.h:736
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:86
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: dummywallet.cpp:85
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:78
const uint256 & GetHash() const
Definition: wallet.h:539
virtual std::unique_ptr< Lock > lock(bool try_lock=false)=0
Return Lock interface.
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:291
Special output type for change outputs only.
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey&#39;ed, it will be returned to the keypool...
Definition: wallet.h:165
CAmount nAmount
Definition: wallet.h:194
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1196
bool HasWallets()
Definition: wallet.cpp:74
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:253
OutputType const type
Definition: wallet.h:147
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:710
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const WalletLocation &location, std::string &error, std::vector< std::string > &warnings)
Definition: wallet.cpp:151
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:1076
CWallet * m_wallet
Definition: wallet.h:1199
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:113
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:64
void Serialize(Stream &s) const
Definition: wallet.h:382
int flags
Definition: bitcoin-tx.cpp:508
bool fInMempool
Definition: wallet.h:324
void setConfirmed()
Definition: wallet.h:538
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:76
static void NotifyUnload(WalletModel *walletModel)
256-bit opaque blob.
Definition: uint256.h:120
void Init(const CWallet *pwalletIn)
Definition: wallet.h:333
void setUnconfirmed()
Definition: wallet.h:536
int64_t atoi64(const char *psz)
CWalletTx(const CWallet *pwalletIn, CTransactionRef arg)
Definition: wallet.h:327
Cachable amount subdivided into watchonly and spendable parts.
Definition: ismine.h:34
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
WalletLocation m_location
Wallet location which includes wallet name (see WalletLocation).
Definition: wallet.h:684
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:70
static void WriteOrderPos(const int64_t &nOrderPos, mapValue_t &mapValue)
Definition: wallet.h:212
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), 0)
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:50
boost::signals2::signal< void(CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:1051
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:740
MasterKeyMap mapMasterKeys
Definition: wallet.h:743
int vout
Definition: wallet.h:223
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:54
Address book data.
Definition: wallet.h:179
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:188
CTxDestination destination
Definition: wallet.h:221
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:302
CInputCoin GetInputCoin() const
Definition: wallet.h:582
void Reset()
Definition: ismine.h:39
int GetSpendSize(unsigned int out, bool use_max_sig=false) const
Definition: wallet.h:471
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:20
void Unserialize(Stream &s)
Definition: wallet.h:235
const CWalletTx * tx
Definition: wallet.h:547
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:598
bool IsScanning()
Definition: wallet.h:836
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:606
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:2017
A wrapper to reserve an address from a wallet.
Definition: wallet.h:140
void AbortRescan()
Definition: wallet.h:834
Definition: wallet.h:219
#define GUARDED_BY(x)
Definition: threadsafety.h:38
void FundTransaction(CWallet *const pwallet, CMutableTransaction &tx, CAmount &fee_out, int &change_position, UniValue options)
Definition: rpcwallet.cpp:2997
RecursiveMutex cs_wallet
Definition: wallet.h:717
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:1061
Optional< int > last_scanned_height
Definition: wallet.h:889
A mutable version of CTransaction.
Definition: transaction.h:366
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:895
bool IsAbortingRescan()
Definition: wallet.h:835
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:791
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:72
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:843
static std::vector< COutput > vCoins
The WalletLocation class provides wallet information.
Definition: walletutil.h:67
std::atomic< int64_t > m_scanning_start
Definition: wallet.h:616
unsigned int nTimeReceived
time received by this node
Definition: wallet.h:292
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
bool isAbandoned() const
Definition: wallet.h:525
bool isReserved() const
Definition: wallet.h:1218
Confirmation(Status s=UNCONFIRMED, int b=0, uint256 h=uint256(), int i=0)
Definition: wallet.h:376
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:143
std::atomic< double > m_scanning_progress
Definition: wallet.h:617
AssertLockHeld(g_cs_orphans)
WalletRescanReserver(CWallet *w)
Definition: wallet.h:1202
CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:144
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:1064
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:769
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
static const CAmount DEFAULT_DISCARD_FEE
-discardfee default
Definition: wallet.h:68
CTransactionRef tx
Definition: wallet.h:349
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig=false) EXCLUSIVE_LOCKS_REQUIRED(wallet -> cs_wallet)
Definition: wallet.cpp:1493
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:70
Legacy class used for deserializing vtxPrev for backwards compatibility.
Definition: wallet.h:231
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:107
~CWallet()
Definition: wallet.h:754
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:86
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:290
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:91