Bitcoin Core  29.1.0
P2P Digital Currency
wallet.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 <addresstype.h>
10 #include <consensus/amount.h>
11 #include <interfaces/chain.h>
12 #include <interfaces/handler.h>
13 #include <kernel/cs_main.h>
14 #include <logging.h>
15 #include <outputtype.h>
16 #include <policy/feerate.h>
17 #include <primitives/transaction.h>
18 #include <script/interpreter.h>
19 #include <script/script.h>
21 #include <sync.h>
22 #include <tinyformat.h>
23 #include <uint256.h>
24 #include <util/fs.h>
25 #include <util/hasher.h>
26 #include <util/result.h>
27 #include <util/string.h>
28 #include <util/time.h>
29 #include <util/ui_change_type.h>
30 #include <wallet/crypter.h>
31 #include <wallet/db.h>
32 #include <wallet/scriptpubkeyman.h>
33 #include <wallet/transaction.h>
34 #include <wallet/types.h>
35 #include <wallet/walletutil.h>
36 
37 #include <atomic>
38 #include <cassert>
39 #include <cstddef>
40 #include <cstdint>
41 #include <functional>
42 #include <limits>
43 #include <map>
44 #include <memory>
45 #include <optional>
46 #include <set>
47 #include <string>
48 #include <unordered_map>
49 #include <utility>
50 #include <vector>
51 
52 #include <boost/signals2/signal.hpp>
53 
54 class CKey;
55 class CKeyID;
56 class CPubKey;
57 class Coin;
58 class SigningProvider;
59 enum class MemPoolRemovalReason;
60 enum class SigningResult;
61 namespace common {
62 enum class PSBTError;
63 } // namespace common
64 namespace interfaces {
65 class Wallet;
66 }
67 namespace wallet {
68 class CWallet;
69 class WalletBatch;
70 enum class DBErrors : int;
71 } // namespace wallet
72 struct CBlockLocator;
73 struct CExtKey;
74 struct FlatSigningProvider;
75 struct KeyOriginInfo;
77 struct SignatureData;
78 
79 using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
80 
81 struct bilingual_str;
82 
83 namespace wallet {
84 struct WalletContext;
85 
88 void WaitForDeleteWallet(std::shared_ptr<CWallet>&& wallet);
89 
90 bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
91 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
92 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start);
93 std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context);
94 std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count);
95 std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name);
96 std::shared_ptr<CWallet> LoadWallet(WalletContext& context, const std::string& name, std::optional<bool> load_on_start, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings);
97 std::shared_ptr<CWallet> CreateWallet(WalletContext& context, const std::string& name, std::optional<bool> load_on_start, DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings);
98 std::shared_ptr<CWallet> RestoreWallet(WalletContext& context, const fs::path& backup_file, const std::string& wallet_name, std::optional<bool> load_on_start, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings, bool load_after_restore = true);
99 std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet);
100 void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
101 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
102 
106 static const CAmount DEFAULT_FALLBACK_FEE = 0;
108 static const CAmount DEFAULT_DISCARD_FEE = 10000;
112 static const CAmount DEFAULT_CONSOLIDATE_FEERATE{10000}; // 10 sat/vbyte
122 constexpr CAmount HIGH_APS_FEE{COIN / 10000};
126 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
128 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS{true};
130 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
132 static const bool DEFAULT_WALLET_RBF = true;
133 static const bool DEFAULT_WALLETBROADCAST = true;
134 static const bool DEFAULT_DISABLE_WALLET = false;
135 static const bool DEFAULT_WALLETCROSSCHAIN = false;
139 constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
143 static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
144 
145 class CCoinControl;
146 
149 
150 static constexpr uint64_t KNOWN_WALLET_FLAGS =
158 
159 static constexpr uint64_t MUTABLE_WALLET_FLAGS =
161 
162 static const std::map<std::string,WalletFlags> WALLET_FLAG_MAP{
163  {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
164  {"blank", WALLET_FLAG_BLANK_WALLET},
165  {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
166  {"last_hardened_xpub_cached", WALLET_FLAG_LAST_HARDENED_XPUB_CACHED},
167  {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
168  {"descriptor_wallet", WALLET_FLAG_DESCRIPTORS},
169  {"external_signer", WALLET_FLAG_EXTERNAL_SIGNER}
170 };
171 
188 {
189 protected:
191  const CWallet* const pwallet;
193  ScriptPubKeyMan* m_spk_man{nullptr};
196  int64_t nIndex{-1};
200  bool fInternal{false};
201 
202 public:
204  explicit ReserveDestination(CWallet* pwallet, OutputType type)
205  : pwallet(pwallet)
206  , type(type) { }
207 
208  ReserveDestination(const ReserveDestination&) = delete;
209  ReserveDestination& operator=(const ReserveDestination&) = delete;
210 
213  {
214  ReturnDestination();
215  }
216 
218  util::Result<CTxDestination> GetReservedDestination(bool internal);
220  void ReturnDestination();
222  void KeepDestination();
223 };
224 
229 {
237  std::optional<std::string> label;
238 
244  std::optional<AddressPurpose> purpose;
245 
253  bool previously_spent{false};
254 
262  std::map<std::string, std::string> receive_requests{};
263 
265  bool IsChange() const { return !label.has_value(); }
266  std::string GetLabel() const { return label ? *label : std::string{}; }
267  void SetLabel(std::string name) { label = std::move(name); }
268 };
269 
270 inline std::string PurposeToString(AddressPurpose p)
271 {
272  switch(p) {
273  case AddressPurpose::RECEIVE: return "receive";
274  case AddressPurpose::SEND: return "send";
275  case AddressPurpose::REFUND: return "refund";
276  } // no default case so the compiler will warn when a new enum as added
277  assert(false);
278 }
279 
280 inline std::optional<AddressPurpose> PurposeFromString(std::string_view s)
281 {
282  if (s == "receive") return AddressPurpose::RECEIVE;
283  else if (s == "send") return AddressPurpose::SEND;
284  else if (s == "refund") return AddressPurpose::REFUND;
285  return {};
286 }
287 
289 {
293 };
294 
295 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
300 {
301 private:
302  CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
303 
304  bool Unlock(const CKeyingMaterial& vMasterKeyIn);
305 
306  std::atomic<bool> fAbortRescan{false};
307  std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
308  std::atomic<bool> m_attaching_chain{false};
309  std::atomic<bool> m_scanning_with_passphrase{false};
310  std::atomic<SteadyClock::time_point> m_scanning_start{SteadyClock::time_point{}};
311  std::atomic<double> m_scanning_progress{0};
312  friend class WalletRescanReserver;
313 
315  int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
316 
318  NodeClock::time_point m_next_resend{GetDefaultNextResend()};
321  bool fBroadcastTransactions = false;
322  // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
323  std::atomic<int64_t> m_best_block_time {0};
324 
325  // First created key time. Used to skip blocks prior to this time.
326  // 'std::numeric_limits<int64_t>::max()' if wallet is blank.
327  std::atomic<int64_t> m_birth_time{std::numeric_limits<int64_t>::max()};
328 
334  typedef std::unordered_multimap<COutPoint, uint256, SaltedOutpointHasher> TxSpends;
335  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
336  void AddToSpends(const COutPoint& outpoint, const uint256& wtxid, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
337  void AddToSpends(const CWalletTx& wtx, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
338 
355  bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const SyncTxState& state, bool fUpdate, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
356 
358  void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
359 
360  enum class TxUpdate { UNCHANGED, CHANGED, NOTIFY_CHANGED };
361 
362  using TryUpdatingStateFn = std::function<TxUpdate(CWalletTx& wtx)>;
363 
365  void RecursiveUpdateTxState(const uint256& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
366  void RecursiveUpdateTxState(WalletBatch* batch, const uint256& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
367 
369  void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
370 
371  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
372 
373  void SyncTransaction(const CTransactionRef& tx, const SyncTxState& state, bool update_tx = true, bool rescanning_old_block = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
374 
376  std::atomic<uint64_t> m_wallet_flags{0};
377 
378  bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& strPurpose);
379 
381  void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
382 
384  void UnsetBlankWalletFlag(WalletBatch& batch) override;
385 
388 
390  std::string m_name;
391 
393  std::unique_ptr<WalletDatabase> m_database;
394 
402  uint256 m_last_block_processed GUARDED_BY(cs_wallet);
403 
409  int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
410 
411  std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
412  std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
413 
414  // Indexed by a unique identifier produced by each ScriptPubKeyMan using
415  // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
416  std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
417 
418  // Appends spk managers into the main 'm_spk_managers'.
419  // Must be the only method adding data to it.
420  void AddScriptPubKeyMan(const uint256& id, std::unique_ptr<ScriptPubKeyMan> spkm_man);
421 
422  // Same as 'AddActiveScriptPubKeyMan' but designed for use within a batch transaction context
423  void AddActiveScriptPubKeyManWithDb(WalletBatch& batch, uint256 id, OutputType type, bool internal);
424 
426  void SetWalletFlagWithDB(WalletBatch& batch, uint64_t flags);
427 
429  std::unordered_map<CScript, std::vector<ScriptPubKeyMan*>, SaltedSipHasher> m_cached_spks;
430 
436  static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings);
437 
438  static NodeClock::time_point GetDefaultNextResend();
439 
440 public:
446 
447  WalletDatabase& GetDatabase() const override
448  {
449  assert(static_cast<bool>(m_database));
450  return *m_database;
451  }
452 
455  const std::string& GetName() const { return m_name; }
456 
457  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
459  unsigned int nMasterKeyMaxID = 0;
460 
462  CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database)
463  : m_chain(chain),
464  m_name(name),
465  m_database(std::move(database))
466  {
467  }
468 
470  {
471  // Should not have slots connected at this point.
472  assert(NotifyUnload.empty());
473  }
474 
475  bool IsCrypted() const;
476  bool IsLocked() const override;
477  bool Lock();
478 
480  bool HaveChain() const { return m_chain ? true : false; }
481 
484  std::unordered_map<uint256, CWalletTx, SaltedTxidHasher> mapWallet GUARDED_BY(cs_wallet);
485 
486  typedef std::multimap<int64_t, CWalletTx*> TxItems;
488 
489  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
490 
491  std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
492  const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
493 
498  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
499 
501  std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
502 
504  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
505 
506  const CWalletTx* GetWalletTx(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
507 
508  std::set<uint256> GetTxConflicts(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
509 
523  int GetTxDepthInMainChain(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
524 
530  int GetTxBlocksToMaturity(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
531  bool IsTxImmatureCoinBase(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
532 
534  bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return IsFeatureSupported(nWalletVersion, wf); }
535 
536  bool IsSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
537 
538  // Whether this or any known scriptPubKey with the same single key has been spent.
539  bool IsSpentKey(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
540  void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
541 
543  util::Result<void> DisplayAddress(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
544 
545  bool IsLockedCoin(const COutPoint& output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
546  bool LockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
547  bool UnlockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
548  bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
549  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
550 
551  /*
552  * Rescan abort properties
553  */
554  void AbortRescan() { fAbortRescan = true; }
555  bool IsAbortingRescan() const { return fAbortRescan; }
556  bool IsScanning() const { return fScanningWallet; }
557  bool IsScanningWithPassphrase() const { return m_scanning_with_passphrase; }
558  SteadyClock::duration ScanningDuration() const { return fScanningWallet ? SteadyClock::now() - m_scanning_start.load() : SteadyClock::duration{}; }
559  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
560 
562  void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
563 
565  void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
566 
567  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; return true; }
568 
570  void LoadAddressPreviouslySpent(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
572  void LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
573 
575  int64_t nRelockTime GUARDED_BY(cs_wallet){0};
576 
577  // Used to prevent concurrent calls to walletpassphrase RPC.
578  Mutex m_unlock_mutex;
579  // Used to prevent deleting the passphrase from memory when it is still in use.
581 
582  bool Unlock(const SecureString& strWalletPassphrase);
583  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
584  bool EncryptWallet(const SecureString& strWalletPassphrase);
585 
586  void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
587  unsigned int ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const;
588 
593  int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
594  DBErrors ReorderTransactions();
595 
596  void MarkDirty();
597 
604  using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
605 
610  CWalletTx* AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true, bool rescanning_old_block = false);
611  bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
612  void transactionAddedToMempool(const CTransactionRef& tx) override;
613  void blockConnected(ChainstateRole role, const interfaces::BlockInfo& block) override;
614  void blockDisconnected(const interfaces::BlockInfo& block) override;
615  void updatedBlockTip() override;
616  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
617 
618  struct ScanResult {
619  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
620 
625  std::optional<int> last_scanned_height;
626 
632  };
633  ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, const bool save_progress);
634  void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override;
636  void SetNextResend() { m_next_resend = GetDefaultNextResend(); }
638  bool ShouldResend() const;
639  void ResubmitWalletTransactions(bool relay, bool force);
640 
641  OutputType TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const;
642 
646  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const;
647  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
648 
664  std::optional<common::PSBTError> FillPSBT(PartiallySignedTransaction& psbtx,
665  bool& complete,
666  int sighash_type = SIGHASH_DEFAULT,
667  bool sign = true,
668  bool bip32derivs = true,
669  size_t* n_signed = nullptr,
670  bool finalize = true) const;
671 
681  void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
682 
684  bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, bool relay) const
685  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
686 
687  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
688  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
689  bool ImportPubKeys(const std::vector<std::pair<CKeyID, bool>>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
690  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);
691 
693  void MaybeUpdateBirthTime(int64_t time);
694 
696  unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
699  bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
700  bool m_signal_rbf{DEFAULT_WALLET_RBF};
701  bool m_allow_fallback_fee{true};
703 
709 
712  CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
713 
718  CFeeRate m_consolidate_feerate{DEFAULT_CONSOLIDATE_FEERATE};
719 
722  OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
729  std::optional<OutputType> m_default_change_type{};
731  CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
732 
734  int64_t m_keypool_size{DEFAULT_KEYPOOL_SIZE};
735 
738 
739  size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
740  bool TopUpKeyPool(unsigned int kpSize = 0);
741 
742  std::optional<int64_t> GetOldestKeyPoolTime() const;
743 
744  // Filter struct for 'ListAddrBookAddresses'
745  struct AddrBookFilter {
746  // Fetch addresses with the provided label
747  std::optional<std::string> m_op_label{std::nullopt};
748  // Don't include change addresses by default
749  bool ignore_change{true};
750  };
751 
755  std::vector<CTxDestination> ListAddrBookAddresses(const std::optional<AddrBookFilter>& filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
756 
760  std::set<std::string> ListAddrBookLabels(const std::optional<AddressPurpose> purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
761 
766  using ListAddrBookFunc = std::function<void(const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose> purpose)>;
767  void ForEachAddrBookEntry(const ListAddrBookFunc& func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
768 
773  void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
774 
775  util::Result<CTxDestination> GetNewDestination(const OutputType type, const std::string label);
776  util::Result<CTxDestination> GetNewChangeDestination(const OutputType type);
777 
778  isminetype IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
779  isminetype IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
784  CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
785  isminetype IsMine(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
786  bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
787  isminetype IsMine(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
789  bool IsFromMe(const CTransaction& tx) const;
790  CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
791  void chainStateFlushed(ChainstateRole role, const CBlockLocator& loc) override;
792 
794 
796  util::Result<void> RemoveTxs(std::vector<uint256>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
797  util::Result<void> RemoveTxs(WalletBatch& batch, std::vector<uint256>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
798 
799  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose);
800 
801  bool DelAddressBook(const CTxDestination& address);
802  bool DelAddressBookWithDB(WalletBatch& batch, const CTxDestination& address);
803 
804  bool IsAddressPreviouslySpent(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
805  bool SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination& dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
806 
807  std::vector<std::string> GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
808  bool SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
809  bool EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
810 
811  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
812 
814  void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr) override;
815 
817  int GetVersion() const { LOCK(cs_wallet); return nWalletVersion; }
818 
820  std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
821 
823  bool HasWalletSpend(const CTransactionRef& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
824 
826  void Flush();
827 
829  void Close();
830 
832  boost::signals2::signal<void ()> NotifyUnload;
833 
838  boost::signals2::signal<void(const CTxDestination& address,
839  const std::string& label, bool isMine,
840  AddressPurpose purpose, ChangeType status)>
842 
847  boost::signals2::signal<void(const uint256& hashTx, ChangeType status)> NotifyTransactionChanged;
848 
850  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
851 
853  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
854 
856  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
857 
862  boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
863 
865  bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
867  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
868 
870  bool TransactionCanBeAbandoned(const uint256& hashTx) const;
871 
872  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
873  bool AbandonTransaction(const uint256& hashTx);
874  bool AbandonTransaction(CWalletTx& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
875 
877  bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
878 
879  /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
880  static std::shared_ptr<CWallet> Create(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings);
881 
886  void postInitProcess();
887 
888  bool BackupWallet(const std::string& strDest) const;
889 
890  /* Returns true if HD is enabled */
891  bool IsHDEnabled() const;
892 
893  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
894  bool CanGetAddresses(bool internal = false) const;
895 
896  /* Returns the time of the first created key or, in case of an import, it could be the time of the first received transaction */
897  int64_t GetBirthTime() const { return m_birth_time; }
898 
905  void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_wallet);
906 
908  void SetWalletFlag(uint64_t flags);
909 
911  void UnsetWalletFlag(uint64_t flag);
912 
914  bool IsWalletFlagSet(uint64_t flag) const override;
915 
919  void InitWalletFlags(uint64_t flags);
921  bool LoadWalletFlags(uint64_t flags);
922 
924  bool IsLegacy() const;
925 
927  std::string GetDisplayName() const override
928  {
929  std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
930  return strprintf("[%s]", wallet_name);
931  };
932 
934  template <typename... Params>
935  void WalletLogPrintf(util::ConstevalFormatString<sizeof...(Params)> wallet_fmt, const Params&... params) const
936  {
937  LogInfo("%s %s", GetDisplayName(), tfm::format(wallet_fmt, params...));
938  };
939 
941  bool UpgradeWallet(int version, bilingual_str& error);
942 
944  std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
945  bool IsActiveScriptPubKeyMan(const ScriptPubKeyMan& spkm) const;
946 
948  std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
949 
951  ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
952 
954  std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script) const;
956  ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
957 
959  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
960  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
961 
963  std::vector<WalletDescriptor> GetWalletDescriptors(const CScript& script) const;
964 
966  LegacyScriptPubKeyMan* GetLegacyScriptPubKeyMan() const;
967  LegacyScriptPubKeyMan* GetOrCreateLegacyScriptPubKeyMan();
968  LegacyDataSPKM* GetLegacyDataSPKM() const;
969  LegacyDataSPKM* GetOrCreateLegacyDataSPKM();
970 
972  void SetupLegacyScriptPubKeyMan();
973 
974  bool WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const override;
975 
976  bool HasEncryptionKeys() const override;
977  bool HaveCryptedKeys() const;
978 
981  {
982  AssertLockHeld(cs_wallet);
983  assert(m_last_block_processed_height >= 0);
984  return m_last_block_processed_height;
985  };
987  {
988  AssertLockHeld(cs_wallet);
989  assert(m_last_block_processed_height >= 0);
990  return m_last_block_processed;
991  }
993  void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
994  {
995  AssertLockHeld(cs_wallet);
996  m_last_block_processed_height = block_height;
997  m_last_block_processed = block_hash;
998  };
999 
1001  void ConnectScriptPubKeyManNotifiers();
1002 
1004  DescriptorScriptPubKeyMan& LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc);
1005 
1010  void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1011 
1016  void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1017 
1022  void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1023 
1025  DescriptorScriptPubKeyMan& SetupDescriptorScriptPubKeyMan(WalletBatch& batch, const CExtKey& master_key, const OutputType& output_type, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1027  void SetupDescriptorScriptPubKeyMans(WalletBatch& batch, const CExtKey& master_key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1028  void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1029 
1031  void SetupOwnDescriptorScriptPubKeyMans(WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1032 
1034  DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1035 
1039  std::optional<bool> IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const;
1040 
1042  ScriptPubKeyMan* AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1043 
1049  bool MigrateToSQLite(bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1050 
1052  std::optional<MigrationData> GetDescriptorsForLegacy(bilingual_str& error) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1053 
1056  util::Result<void> ApplyMigrationData(WalletBatch& local_wallet_batch, MigrationData& data) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1057 
1059  bool CanGrindR() const;
1060 
1062  void CacheNewScriptPubKeys(const std::set<CScript>& spks, ScriptPubKeyMan* spkm);
1063 
1064  void TopUpCallback(const std::set<CScript>& spks, ScriptPubKeyMan* spkm) override;
1065 
1067  std::set<CExtPubKey> GetActiveHDPubKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1068 
1071  std::optional<CKey> GetKey(const CKeyID& keyid) const;
1072 };
1073 
1078 void MaybeResendWalletTxs(WalletContext& context);
1079 
1082 {
1083 private:
1084  using Clock = std::chrono::steady_clock;
1085  using NowFn = std::function<Clock::time_point()>;
1087  bool m_could_reserve{false};
1089 public:
1091 
1092  bool reserve(bool with_passphrase = false)
1093  {
1094  assert(!m_could_reserve);
1095  if (m_wallet.fScanningWallet.exchange(true)) {
1096  return false;
1097  }
1098  m_wallet.m_scanning_with_passphrase.exchange(with_passphrase);
1099  m_wallet.m_scanning_start = SteadyClock::now();
1100  m_wallet.m_scanning_progress = 0;
1101  m_could_reserve = true;
1102  return true;
1103  }
1104 
1105  bool isReserved() const
1106  {
1107  return (m_could_reserve && m_wallet.fScanningWallet);
1108  }
1109 
1110  Clock::time_point now() const { return m_now ? m_now() : Clock::now(); };
1111 
1112  void setNow(NowFn now) { m_now = std::move(now); }
1113 
1115  {
1116  if (m_could_reserve) {
1117  m_wallet.fScanningWallet = false;
1118  m_wallet.m_scanning_with_passphrase = false;
1119  }
1120  }
1121 };
1122 
1124 bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1125 
1127 bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1128 
1130  std::string wallet_name;
1131  std::shared_ptr<CWallet> wallet;
1132  std::shared_ptr<CWallet> watchonly_wallet;
1133  std::shared_ptr<CWallet> solvables_wallet;
1135 };
1136 
1138 [[nodiscard]] util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context);
1140 [[nodiscard]] util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet> local_wallet, const SecureString& passphrase, WalletContext& context, bool was_loaded);
1141 } // namespace wallet
1142 
1143 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:631
PSBTError
Definition: types.h:17
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:148
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we support the named feature
Definition: wallet.h:534
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::chrono::time_point< NodeClock > time_point
Definition: time.h:19
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:110
AssertLockHeld(pool.cs)
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:411
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:139
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:143
assert(!tx.IsCoinBase())
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:79
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:123
Never set in current code may be present in older wallet databases.
std::optional< int > last_scanned_height
Definition: wallet.h:625
std::optional< AddressPurpose > purpose
Address purpose which was originally recorded for payment protocol support but now serves as a cached...
Definition: wallet.h:244
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey&#39;ed, it will be returned to the keypool...
Definition: wallet.h:212
A UTXO entry.
Definition: coins.h:32
Bilingual messages:
Definition: translation.h:24
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:47
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:624
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:149
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:35
std::string GetLabel() const
Definition: wallet.h:266
std::string m_notify_tx_changed_script
Notify external script when a wallet transaction comes in or is updated (handled by -walletnotify) ...
Definition: wallet.h:737
std::optional< AddressPurpose > PurposeFromString(std::string_view s)
Definition: wallet.h:280
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:455
std::shared_ptr< CWallet > LoadWallet(WalletContext &context, const std::string &name, std::optional< bool > load_on_start, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:370
Definition: key.h:227
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:867
struct containing information needed for migrating legacy wallets to descriptor wallets ...
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:564
void setNow(NowFn now)
Definition: wallet.h:1112
WalletRescanReserver(CWallet &w)
Definition: wallet.h:1090
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:58
MasterKeyMap mapMasterKeys
Definition: wallet.h:458
WalletDatabase & GetDatabase() const override
Definition: wallet.h:447
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
std::string PurposeToString(AddressPurpose p)
Definition: wallet.h:270
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:191
CTxDestination address
The destination.
Definition: wallet.h:198
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:445
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:107
std::variant< TxStateConfirmed, TxStateInMempool, TxStateInactive > SyncTxState
Subset of states transaction sync logic is implemented to handle.
Definition: transaction.h:81
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:134
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1081
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:486
A version of CTransaction with the PSBT format.
Definition: psbt.h:950
bool reserve(bool with_passphrase=false)
Definition: wallet.h:1092
SigningResult
Definition: signmessage.h:43
Access to the wallet database.
Definition: walletdb.h:195
RecursiveMutex m_relock_mutex
Definition: wallet.h:580
boost::signals2::signal< void()> NotifyUnload
Wallet is about to be unloaded.
Definition: wallet.h:832
boost::signals2::signal< void(const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:847
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
double ScanningProgress() const
Definition: wallet.h:559
std::function< void(const CTxDestination &dest, const std::string &label, bool is_change, const std::optional< AddressPurpose > purpose)> ListAddrBookFunc
Walk-through the address book entries.
Definition: wallet.h:766
OutputType
Definition: outputtype.h:17
std::function< Clock::time_point()> NowFn
Definition: wallet.h:1085
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:71
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:141
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:159
Result CommitTransaction(CWallet &wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:356
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:132
void MaybeResendWalletTxs(WalletContext &context)
Called periodically by the schedule thread.
Definition: wallet.cpp:2165
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:120
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:126
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:416
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:853
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static DBErrors LoadWalletFlags(CWallet *pwallet, DatabaseBatch &batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:482
constexpr CAmount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:104
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:176
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:387
std::function< TxUpdate(CWalletTx &wtx)> TryUpdatingStateFn
Definition: wallet.h:362
CWallet(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:462
AddressPurpose
Address purpose field that has been been stored with wallet sending and receiving addresses since BIP...
Definition: types.h:61
Indicates that the wallet needs an external signer.
Definition: walletutil.h:77
bool fSubtractFeeFromAmount
Definition: wallet.h:292
std::underlying_type< isminetype >::type isminefilter
used for bitflags of isminetype
Definition: wallet.h:48
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
Definition: wallet.cpp:252
std::shared_ptr< CWallet > wallet
Definition: wallet.h:1131
std::string wallet_name
Definition: wallet.h:1130
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
Definition: wallet.h:124
std::chrono::steady_clock Clock
Definition: wallet.h:1084
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:25
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:865
An input of a transaction.
Definition: transaction.h:66
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:150
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:980
#define LOCK(cs)
Definition: sync.h:257
const char * name
Definition: rest.cpp:49
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:130
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:412
std::optional< std::string > label
Address label which is always nullopt for change addresses.
Definition: wallet.h:237
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:993
Chain notifications.
Definition: chain.h:317
int nWalletVersion GUARDED_BY(cs_wallet)
the current wallet version: clients below this version are not able to load the wallet ...
Definition: wallet.h:315
void WalletLogPrintf(util::ConstevalFormatString< sizeof...(Params)> wallet_fmt, const Params &... params) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Definition: wallet.h:935
An encapsulated public key.
Definition: pubkey.h:33
std::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:78
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: types.h:41
static const CAmount DEFAULT_DISCARD_FEE
-discardfee default
Definition: wallet.h:108
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:220
bool IsFeatureSupported(int wallet_version, int feature_version)
Definition: walletutil.cpp:35
CTxDestination dest
Definition: wallet.h:290
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:15
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:299
An output of a transaction.
Definition: transaction.h:149
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:457
std::string m_name
Wallet name: relative directory name or "" for default wallet.
Definition: wallet.h:390
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
static DBErrors LoadMinVersion(CWallet *pwallet, DatabaseBatch &batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:469
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:162
A wrapper for a compile-time partially validated format string.
Definition: string.h:92
TxItems wtxOrdered
Definition: wallet.h:487
is a home for public enum and struct type definitions that are used by internally by wallet code...
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:106
util::Result< MigrationResult > MigrateLegacyToDescriptor(const std::string &wallet_name, const SecureString &passphrase, WalletContext &context)
Do all steps to migrate a legacy wallet to a descriptor wallet.
Definition: wallet.cpp:4413
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:850
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:94
std::shared_ptr< CWallet > solvables_wallet
Definition: wallet.h:1133
Descriptor with some wallet metadata.
Definition: walletutil.h:84
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:133
Definition: args.cpp:868
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:161
std::unordered_map< CScript, std::vector< ScriptPubKeyMan * >, SaltedSipHasher > m_cached_spks
Cache of descriptor ScriptPubKeys used for IsMine. Maps ScriptPubKey to set of spkms.
Definition: wallet.h:429
#define LogInfo(...)
Definition: logging.h:356
int flags
Definition: bitcoin-tx.cpp:536
std::shared_ptr< CWallet > GetWallet(WalletContext &context, const std::string &name)
Definition: wallet.cpp:204
static int sign(const secp256k1_context *ctx, struct signer_secrets *signer_secrets, struct signer *signer, const secp256k1_musig_keyagg_cache *cache, const unsigned char *msg32, unsigned char *sig64)
Definition: musig.c:105
DatabaseStatus
Definition: db.h:205
static void NotifyUnload(WalletModel *walletModel)
256-bit opaque blob.
Definition: uint256.h:201
bool IsChange() const
Accessor methods.
Definition: wallet.h:265
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:191
An interface to be implemented by keystores that support signing.
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:128
const CChainParams & Params()
Return the currently selected parameters.
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Definition: wallet.h:604
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
std::shared_ptr< CWallet > RestoreWallet(WalletContext &context, const fs::path &backup_file, const std::string &wallet_name, std::optional< bool > load_on_start, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings, bool load_after_restore)
Definition: wallet.cpp:495
std::shared_ptr< CWallet > watchonly_wallet
Definition: wallet.h:1132
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:140
int64_t GetBirthTime() const
Definition: wallet.h:897
bool IsAbortingRescan() const
Definition: wallet.h:555
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:862
CAmount nAmount
Definition: wallet.h:291
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
Address book data.
Definition: wallet.h:228
OutputType const type
Definition: wallet.h:194
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:213
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:137
WalletContext struct containing references to state shared between CWallet instances, like the reference to the chain interface, and the list of opened wallets.
Definition: context.h:36
A wrapper to reserve an address from a wallet.
Definition: wallet.h:187
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:480
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
void SetLabel(std::string name)
Definition: wallet.h:267
static int count
bool IsScanningWithPassphrase() const
Definition: wallet.h:557
SteadyClock::duration ScanningDuration() const
Definition: wallet.h:558
std::unordered_multimap< COutPoint, uint256, SaltedOutpointHasher > TxSpends
Used to keep track of spent outpoints, and detect and report conflicts (double-spends or mutated tran...
Definition: wallet.h:334
A mutable version of CTransaction.
Definition: transaction.h:377
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:986
void SetNextResend()
Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average...
Definition: wallet.h:636
std::unique_ptr< WalletDatabase > m_database
Internal database handle.
Definition: wallet.h:393
An encapsulated private key.
Definition: key.h:34
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:295
static const bool DEFAULT_WALLETCROSSCHAIN
Definition: wallet.h:135
constexpr CAmount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:122
static const CAmount DEFAULT_CONSOLIDATE_FEERATE
-consolidatefeerate default
Definition: wallet.h:112
std::shared_ptr< CWallet > CreateWallet(WalletContext &context, const std::string &name, std::optional< bool > load_on_start, DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:383
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
Definition: wallet.h:204
ChangeType
General change type (added, updated, removed).
Definition: ui_change_type.h:9
boost::signals2::signal< void(const CTxDestination &address, const std::string &label, bool isMine, AddressPurpose purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:841
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:32
std::shared_ptr< CWallet > GetDefaultWallet(WalletContext &context, size_t &count)
Definition: wallet.cpp:197
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:149
static std::set< std::string > g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex)
bool IsScanning() const
Definition: wallet.h:556
Coin Control Features.
Definition: coincontrol.h:80
An instance of this class represents one database.
Definition: db.h:130
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:856
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:62
Clock::time_point now() const
Definition: wallet.h:1110
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2992
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:128
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
New diagram wasn&#39;t strictly superior.