Bitcoin Core  26.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 enum class TransactionError;
62 namespace interfaces {
63 class Wallet;
64 }
65 namespace wallet {
66 class CWallet;
67 class WalletBatch;
68 enum class DBErrors : int;
69 } // namespace wallet
70 struct CBlockLocator;
71 struct CExtKey;
72 struct FlatSigningProvider;
73 struct KeyOriginInfo;
75 struct SignatureData;
76 
77 using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
78 
79 struct bilingual_str;
80 
81 namespace wallet {
82 struct WalletContext;
83 
89 void UnloadWallet(std::shared_ptr<CWallet>&& wallet);
90 
91 bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
92 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
93 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start);
94 std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context);
95 std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count);
96 std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name);
97 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);
98 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);
99 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);
100 std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet);
101 void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
102 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
103 
107 static const CAmount DEFAULT_FALLBACK_FEE = 0;
109 static const CAmount DEFAULT_DISCARD_FEE = 10000;
113 static const CAmount DEFAULT_CONSOLIDATE_FEERATE{10000}; // 10 sat/vbyte
123 constexpr CAmount HIGH_APS_FEE{COIN / 10000};
127 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
129 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS{true};
131 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
133 static const bool DEFAULT_WALLET_RBF = true;
134 static const bool DEFAULT_WALLETBROADCAST = true;
135 static const bool DEFAULT_DISABLE_WALLET = false;
136 static const bool DEFAULT_WALLETCROSSCHAIN = false;
140 constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
144 static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
145 
146 class CCoinControl;
147 
150 
151 static constexpr uint64_t KNOWN_WALLET_FLAGS =
159 
160 static constexpr uint64_t MUTABLE_WALLET_FLAGS =
162 
163 static const std::map<std::string,WalletFlags> WALLET_FLAG_MAP{
164  {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
165  {"blank", WALLET_FLAG_BLANK_WALLET},
166  {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
167  {"last_hardened_xpub_cached", WALLET_FLAG_LAST_HARDENED_XPUB_CACHED},
168  {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
169  {"descriptor_wallet", WALLET_FLAG_DESCRIPTORS},
170  {"external_signer", WALLET_FLAG_EXTERNAL_SIGNER}
171 };
172 
189 {
190 protected:
192  const CWallet* const pwallet;
194  ScriptPubKeyMan* m_spk_man{nullptr};
197  int64_t nIndex{-1};
201  bool fInternal{false};
202 
203 public:
205  explicit ReserveDestination(CWallet* pwallet, OutputType type)
206  : pwallet(pwallet)
207  , type(type) { }
208 
209  ReserveDestination(const ReserveDestination&) = delete;
210  ReserveDestination& operator=(const ReserveDestination&) = delete;
211 
214  {
215  ReturnDestination();
216  }
217 
219  util::Result<CTxDestination> GetReservedDestination(bool internal);
221  void ReturnDestination();
223  void KeepDestination();
224 };
225 
230 {
238  std::optional<std::string> label;
239 
245  std::optional<AddressPurpose> purpose;
246 
254  bool previously_spent{false};
255 
263  std::map<std::string, std::string> receive_requests{};
264 
266  bool IsChange() const { return !label.has_value(); }
267  std::string GetLabel() const { return label ? *label : std::string{}; }
268  void SetLabel(std::string name) { label = std::move(name); }
269 };
270 
271 inline std::string PurposeToString(AddressPurpose p)
272 {
273  switch(p) {
274  case AddressPurpose::RECEIVE: return "receive";
275  case AddressPurpose::SEND: return "send";
276  case AddressPurpose::REFUND: return "refund";
277  } // no default case so the compiler will warn when a new enum as added
278  assert(false);
279 }
280 
281 inline std::optional<AddressPurpose> PurposeFromString(std::string_view s)
282 {
283  if (s == "receive") return AddressPurpose::RECEIVE;
284  else if (s == "send") return AddressPurpose::SEND;
285  else if (s == "refund") return AddressPurpose::REFUND;
286  return {};
287 }
288 
290 {
294 };
295 
296 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
301 {
302 private:
303  CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
304 
305  bool Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys = false);
306 
307  std::atomic<bool> fAbortRescan{false};
308  std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
309  std::atomic<bool> m_attaching_chain{false};
310  std::atomic<bool> m_scanning_with_passphrase{false};
311  std::atomic<SteadyClock::time_point> m_scanning_start{SteadyClock::time_point{}};
312  std::atomic<double> m_scanning_progress{0};
313  friend class WalletRescanReserver;
314 
316  int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
317 
319  NodeClock::time_point m_next_resend{GetDefaultNextResend()};
322  bool fBroadcastTransactions = false;
323  // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
324  std::atomic<int64_t> m_best_block_time {0};
325 
326  // First created key time. Used to skip blocks prior to this time.
327  // 'std::numeric_limits<int64_t>::max()' if wallet is blank.
328  std::atomic<int64_t> m_birth_time{std::numeric_limits<int64_t>::max()};
329 
335  typedef std::unordered_multimap<COutPoint, uint256, SaltedOutpointHasher> TxSpends;
336  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
337  void AddToSpends(const COutPoint& outpoint, const uint256& wtxid, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
338  void AddToSpends(const CWalletTx& wtx, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
339 
356  bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const SyncTxState& state, bool fUpdate, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
357 
359  void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
360 
361  enum class TxUpdate { UNCHANGED, CHANGED, NOTIFY_CHANGED };
362 
363  using TryUpdatingStateFn = std::function<TxUpdate(CWalletTx& wtx)>;
364 
366  void RecursiveUpdateTxState(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 
427  static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings);
428 
429  static NodeClock::time_point GetDefaultNextResend();
430 
431 public:
437 
438  WalletDatabase& GetDatabase() const override
439  {
440  assert(static_cast<bool>(m_database));
441  return *m_database;
442  }
443 
446  const std::string& GetName() const { return m_name; }
447 
448  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
450  unsigned int nMasterKeyMaxID = 0;
451 
453  CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database)
454  : m_chain(chain),
455  m_name(name),
456  m_database(std::move(database))
457  {
458  }
459 
461  {
462  // Should not have slots connected at this point.
463  assert(NotifyUnload.empty());
464  }
465 
466  bool IsCrypted() const;
467  bool IsLocked() const override;
468  bool Lock();
469 
471  bool HaveChain() const { return m_chain ? true : false; }
472 
475  std::unordered_map<uint256, CWalletTx, SaltedTxidHasher> mapWallet GUARDED_BY(cs_wallet);
476 
477  typedef std::multimap<int64_t, CWalletTx*> TxItems;
479 
480  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
481 
482  std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
483  const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
484 
489  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
490 
492  std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
493 
495  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
496 
497  const CWalletTx* GetWalletTx(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
498 
499  std::set<uint256> GetTxConflicts(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
500 
507  int GetTxDepthInMainChain(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
508  bool IsTxInMainChain(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
509  {
510  AssertLockHeld(cs_wallet);
511  return GetTxDepthInMainChain(wtx) > 0;
512  }
513 
519  int GetTxBlocksToMaturity(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
520  bool IsTxImmatureCoinBase(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
521 
523  bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return IsFeatureSupported(nWalletVersion, wf); }
524 
525  bool IsSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
526 
527  // Whether this or any known scriptPubKey with the same single key has been spent.
528  bool IsSpentKey(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
529  void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
530 
532  bool DisplayAddress(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
533 
534  bool IsLockedCoin(const COutPoint& output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
535  bool LockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
536  bool UnlockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
537  bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
538  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
539 
540  /*
541  * Rescan abort properties
542  */
543  void AbortRescan() { fAbortRescan = true; }
544  bool IsAbortingRescan() const { return fAbortRescan; }
545  bool IsScanning() const { return fScanningWallet; }
546  bool IsScanningWithPassphrase() const { return m_scanning_with_passphrase; }
547  SteadyClock::duration ScanningDuration() const { return fScanningWallet ? SteadyClock::now() - m_scanning_start.load() : SteadyClock::duration{}; }
548  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
549 
551  void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
552 
554  void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
555 
556  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; return true; }
557 
559  void LoadAddressPreviouslySpent(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
561  void LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
562 
564  int64_t nRelockTime GUARDED_BY(cs_wallet){0};
565 
566  // Used to prevent concurrent calls to walletpassphrase RPC.
567  Mutex m_unlock_mutex;
568  // Used to prevent deleting the passphrase from memory when it is still in use.
570 
571  bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
572  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
573  bool EncryptWallet(const SecureString& strWalletPassphrase);
574 
575  void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
576  unsigned int ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const;
577 
582  int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
583  DBErrors ReorderTransactions();
584 
585  void MarkDirty();
586 
593  using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
594 
599  CWalletTx* AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true, bool rescanning_old_block = false);
600  bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
601  void transactionAddedToMempool(const CTransactionRef& tx) override;
602  void blockConnected(ChainstateRole role, const interfaces::BlockInfo& block) override;
603  void blockDisconnected(const interfaces::BlockInfo& block) override;
604  void updatedBlockTip() override;
605  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
606 
607  struct ScanResult {
608  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
609 
614  std::optional<int> last_scanned_height;
615 
621  };
622  ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, const bool save_progress);
623  void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override;
625  void SetNextResend() { m_next_resend = GetDefaultNextResend(); }
627  bool ShouldResend() const;
628  void ResubmitWalletTransactions(bool relay, bool force);
629 
630  OutputType TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const;
631 
635  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const;
636  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
637 
654  bool& complete,
655  int sighash_type = SIGHASH_DEFAULT,
656  bool sign = true,
657  bool bip32derivs = true,
658  size_t* n_signed = nullptr,
659  bool finalize = true) const;
660 
670  void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
671 
673  bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, bool relay) const
674  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
675 
676  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
677  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
678  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);
679  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);
680 
682  void MaybeUpdateBirthTime(int64_t time);
683 
685  unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
688  bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
689  bool m_signal_rbf{DEFAULT_WALLET_RBF};
690  bool m_allow_fallback_fee{true};
692 
698 
701  CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
702 
707  CFeeRate m_consolidate_feerate{DEFAULT_CONSOLIDATE_FEERATE};
708 
711  OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
718  std::optional<OutputType> m_default_change_type{};
720  CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
721 
723  int64_t m_keypool_size{DEFAULT_KEYPOOL_SIZE};
724 
727 
728  size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
729  bool TopUpKeyPool(unsigned int kpSize = 0);
730 
731  std::optional<int64_t> GetOldestKeyPoolTime() const;
732 
733  // Filter struct for 'ListAddrBookAddresses'
734  struct AddrBookFilter {
735  // Fetch addresses with the provided label
736  std::optional<std::string> m_op_label{std::nullopt};
737  // Don't include change addresses by default
738  bool ignore_change{true};
739  };
740 
744  std::vector<CTxDestination> ListAddrBookAddresses(const std::optional<AddrBookFilter>& filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
745 
749  std::set<std::string> ListAddrBookLabels(const std::optional<AddressPurpose> purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
750 
755  using ListAddrBookFunc = std::function<void(const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose> purpose)>;
756  void ForEachAddrBookEntry(const ListAddrBookFunc& func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
757 
762  void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
763 
764  util::Result<CTxDestination> GetNewDestination(const OutputType type, const std::string label);
765  util::Result<CTxDestination> GetNewChangeDestination(const OutputType type);
766 
767  isminetype IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
768  isminetype IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
773  CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
774  isminetype IsMine(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
775  bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
776  isminetype IsMine(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
778  bool IsFromMe(const CTransaction& tx) const;
779  CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
780  void chainStateFlushed(ChainstateRole role, const CBlockLocator& loc) override;
781 
783  DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
784 
785  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose);
786 
787  bool DelAddressBook(const CTxDestination& address);
788 
789  bool IsAddressPreviouslySpent(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
790  bool SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination& dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
791 
792  std::vector<std::string> GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
793  bool SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
794  bool EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
795 
796  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
797 
799  void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr) override;
800 
802  int GetVersion() const { LOCK(cs_wallet); return nWalletVersion; }
803 
805  std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
806 
808  bool HasWalletSpend(const CTransactionRef& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
809 
811  void Flush();
812 
814  void Close();
815 
817  boost::signals2::signal<void ()> NotifyUnload;
818 
823  boost::signals2::signal<void(const CTxDestination& address,
824  const std::string& label, bool isMine,
825  AddressPurpose purpose, ChangeType status)>
827 
832  boost::signals2::signal<void(const uint256& hashTx, ChangeType status)> NotifyTransactionChanged;
833 
835  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
836 
838  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
839 
841  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
842 
847  boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
848 
850  bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
852  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
853 
855  bool TransactionCanBeAbandoned(const uint256& hashTx) const;
856 
857  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
858  bool AbandonTransaction(const uint256& hashTx);
859 
861  bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
862 
863  /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
864  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);
865 
870  void postInitProcess();
871 
872  bool BackupWallet(const std::string& strDest) const;
873 
874  /* Returns true if HD is enabled */
875  bool IsHDEnabled() const;
876 
877  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
878  bool CanGetAddresses(bool internal = false) const;
879 
880  /* Returns the time of the first created key or, in case of an import, it could be the time of the first received transaction */
881  int64_t GetBirthTime() const { return m_birth_time; }
882 
889  void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_wallet);
890 
892  void SetWalletFlag(uint64_t flags);
893 
895  void UnsetWalletFlag(uint64_t flag);
896 
898  bool IsWalletFlagSet(uint64_t flag) const override;
899 
903  void InitWalletFlags(uint64_t flags);
905  bool LoadWalletFlags(uint64_t flags);
906 
908  bool IsLegacy() const;
909 
911  std::string GetDisplayName() const override
912  {
913  std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
914  return strprintf("[%s]", wallet_name);
915  };
916 
918  template <typename... Params>
919  void WalletLogPrintf(const char* fmt, Params... parameters) const
920  {
921  LogPrintf(("%s " + std::string{fmt}).c_str(), GetDisplayName(), parameters...);
922  };
923 
925  bool UpgradeWallet(int version, bilingual_str& error);
926 
928  std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
929 
931  std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
932 
934  ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
935 
937  std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script) const;
939  ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
940 
942  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
943  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
944 
946  std::vector<WalletDescriptor> GetWalletDescriptors(const CScript& script) const;
947 
949  LegacyScriptPubKeyMan* GetLegacyScriptPubKeyMan() const;
950  LegacyScriptPubKeyMan* GetOrCreateLegacyScriptPubKeyMan();
951 
953  void SetupLegacyScriptPubKeyMan();
954 
955  const CKeyingMaterial& GetEncryptionKey() const override;
956  bool HasEncryptionKeys() const override;
957 
960  {
961  AssertLockHeld(cs_wallet);
962  assert(m_last_block_processed_height >= 0);
963  return m_last_block_processed_height;
964  };
966  {
967  AssertLockHeld(cs_wallet);
968  assert(m_last_block_processed_height >= 0);
969  return m_last_block_processed;
970  }
972  void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
973  {
974  AssertLockHeld(cs_wallet);
975  m_last_block_processed_height = block_height;
976  m_last_block_processed = block_hash;
977  };
978 
980  void ConnectScriptPubKeyManNotifiers();
981 
983  void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc);
984 
989  void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
990 
995  void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
996 
1001  void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1002 
1004  void SetupDescriptorScriptPubKeyMans(const CExtKey& master_key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1005  void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1006 
1008  DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1009 
1013  std::optional<bool> IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const;
1014 
1016  ScriptPubKeyMan* AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1017 
1023  bool MigrateToSQLite(bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1024 
1026  std::optional<MigrationData> GetDescriptorsForLegacy(bilingual_str& error) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1027 
1030  bool ApplyMigrationData(MigrationData& data, bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1031 
1033  bool CanGrindR() const;
1034 };
1035 
1041 
1044 {
1045 private:
1046  using Clock = std::chrono::steady_clock;
1047  using NowFn = std::function<Clock::time_point()>;
1049  bool m_could_reserve{false};
1051 public:
1053 
1054  bool reserve(bool with_passphrase = false)
1055  {
1056  assert(!m_could_reserve);
1057  if (m_wallet.fScanningWallet.exchange(true)) {
1058  return false;
1059  }
1060  m_wallet.m_scanning_with_passphrase.exchange(with_passphrase);
1061  m_wallet.m_scanning_start = SteadyClock::now();
1062  m_wallet.m_scanning_progress = 0;
1063  m_could_reserve = true;
1064  return true;
1065  }
1066 
1067  bool isReserved() const
1068  {
1069  return (m_could_reserve && m_wallet.fScanningWallet);
1070  }
1071 
1072  Clock::time_point now() const { return m_now ? m_now() : Clock::now(); };
1073 
1074  void setNow(NowFn now) { m_now = std::move(now); }
1075 
1077  {
1078  if (m_could_reserve) {
1079  m_wallet.fScanningWallet = false;
1080  m_wallet.m_scanning_with_passphrase = false;
1081  }
1082  }
1083 };
1084 
1086 bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1087 
1089 bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1090 
1092  std::string wallet_name;
1093  std::shared_ptr<CWallet> wallet;
1094  std::shared_ptr<CWallet> watchonly_wallet;
1095  std::shared_ptr<CWallet> solvables_wallet;
1097 };
1098 
1100 [[nodiscard]] util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context);
1101 } // namespace wallet
1102 
1103 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:620
static const std::string sighash
Definition: sighash.json.h:3
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:149
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we support the named feature
Definition: wallet.h:523
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:17
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:111
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:140
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:144
assert(!tx.IsCoinBase())
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:77
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:614
std::optional< AddressPurpose > purpose
Address purpose which was originally recorded for payment protocol support but now serves as a cached...
Definition: wallet.h:245
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey&#39;ed, it will be returned to the keypool...
Definition: wallet.h:213
A UTXO entry.
Definition: coins.h:31
Bilingual messages:
Definition: translation.h:18
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:1162
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:613
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:144
std::string GetLabel() const
Definition: wallet.h:267
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:726
std::optional< AddressPurpose > PurposeFromString(std::string_view s)
Definition: wallet.h:281
SigningResult
Definition: message.h:43
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:446
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:360
Definition: key.h:208
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:852
struct containing information needed for migrating legacy wallets to descriptor wallets ...
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:561
void setNow(NowFn now)
Definition: wallet.h:1074
WalletRescanReserver(CWallet &w)
Definition: wallet.h:1052
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:58
MasterKeyMap mapMasterKeys
Definition: wallet.h:449
WalletDatabase & GetDatabase() const override
Definition: wallet.h:438
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
std::string PurposeToString(AddressPurpose p)
Definition: wallet.h:271
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:192
CTxDestination address
The destination.
Definition: wallet.h:199
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:436
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:101
std::variant< TxStateConfirmed, TxStateInMempool, TxStateInactive > SyncTxState
Subset of states transaction sync logic is implemented to handle.
Definition: transaction.h:76
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:135
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1043
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:477
A version of CTransaction with the PSBT format.
Definition: psbt.h:946
bool reserve(bool with_passphrase=false)
Definition: wallet.h:1054
Access to the wallet database.
Definition: walletdb.h:190
RecursiveMutex m_relock_mutex
Definition: wallet.h:569
boost::signals2::signal< void()> NotifyUnload
Wallet is about to be unloaded.
Definition: wallet.h:817
boost::signals2::signal< void(const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:832
double ScanningProgress() const
Definition: wallet.h:548
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:755
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:33
OutputType
Definition: outputtype.h:17
std::function< Clock::time_point()> NowFn
Definition: wallet.h:1047
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:142
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:160
Result CommitTransaction(CWallet &wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:357
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:133
void MaybeResendWalletTxs(WalletContext &context)
Called periodically by the schedule thread.
Definition: wallet.cpp:2096
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:121
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:127
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:838
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:462
constexpr CAmount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:105
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:171
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:387
std::function< TxUpdate(CWalletTx &wtx)> TryUpdatingStateFn
Definition: wallet.h:363
CWallet(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:453
AddressPurpose
Address purpose field that has been been stored with wallet sending and receiving addresses since BIP...
Definition: types.h:60
Indicates that the wallet needs an external signer.
Definition: walletutil.h:77
bool fSubtractFeeFromAmount
Definition: wallet.h:293
std::underlying_type< isminetype >::type isminefilter
used for bitflags of isminetype
Definition: wallet.h:43
std::shared_ptr< CWallet > wallet
Definition: wallet.h:1093
std::string wallet_name
Definition: wallet.h:1092
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
Definition: wallet.h:125
std::chrono::steady_clock Clock
Definition: wallet.h:1046
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:850
An input of a transaction.
Definition: transaction.h:74
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:151
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:959
#define LOCK(cs)
Definition: sync.h:258
const char * name
Definition: rest.cpp:45
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:131
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:238
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:972
Chain notifications.
Definition: chain.h:308
int nWalletVersion GUARDED_BY(cs_wallet)
the current wallet version: clients below this version are not able to load the wallet ...
Definition: wallet.h:316
An encapsulated public key.
Definition: pubkey.h:33
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: types.h:40
static const CAmount DEFAULT_DISCARD_FEE
-discardfee default
Definition: wallet.h:109
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:207
bool IsFeatureSupported(int wallet_version, int feature_version)
Definition: walletutil.cpp:33
CTxDestination dest
Definition: wallet.h:291
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:15
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
WalletContext context
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:300
An output of a transaction.
Definition: transaction.h:157
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:448
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:35
static DBErrors LoadMinVersion(CWallet *pwallet, DatabaseBatch &batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
Definition: walletdb.cpp:450
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:163
TxItems wtxOrdered
Definition: wallet.h:478
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:239
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:107
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:4193
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:835
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:90
std::shared_ptr< CWallet > solvables_wallet
Definition: wallet.h:1095
bool IsTxInMainChain(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:508
Descriptor with some wallet metadata.
Definition: walletutil.h:84
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:134
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:152
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:129
int flags
Definition: bitcoin-tx.cpp:528
std::shared_ptr< CWallet > GetWallet(WalletContext &context, const std::string &name)
Definition: wallet.cpp:191
DatabaseStatus
Definition: db.h:197
static void NotifyUnload(WalletModel *walletModel)
256-bit opaque blob.
Definition: uint256.h:106
bool IsChange() const
Accessor methods.
Definition: wallet.h:266
void WalletLogPrintf(const char *fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Definition: wallet.h:919
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:178
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:122
bool error(const char *fmt, const Args &... args)
Definition: logging.h:262
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:593
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:412
std::shared_ptr< CWallet > watchonly_wallet
Definition: wallet.h:1094
int64_t GetBirthTime() const
Definition: wallet.h:881
bool IsAbortingRescan() const
Definition: wallet.h:544
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:847
CAmount nAmount
Definition: wallet.h:292
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
Address book data.
Definition: wallet.h:229
OutputType const type
Definition: wallet.h:195
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:200
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:138
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:35
A wrapper to reserve an address from a wallet.
Definition: wallet.h:188
TransactionError
Definition: error.h:22
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:471
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
void SetLabel(std::string name)
Definition: wallet.h:268
static int count
bool IsScanningWithPassphrase() const
Definition: wallet.h:546
SteadyClock::duration ScanningDuration() const
Definition: wallet.h:547
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:335
A mutable version of CTransaction.
Definition: transaction.h:379
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:965
void SetNextResend()
Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average...
Definition: wallet.h:625
std::unique_ptr< WalletDatabase > m_database
Internal database handle.
Definition: wallet.h:393
An encapsulated private key.
Definition: key.h:32
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:294
static const bool DEFAULT_WALLETCROSSCHAIN
Definition: wallet.h:136
constexpr CAmount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:123
static const CAmount DEFAULT_CONSOLIDATE_FEERATE
-consolidatefeerate default
Definition: wallet.h:113
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:373
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
Definition: wallet.h:205
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:826
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)
Definition: wallet.cpp:478
#define LogPrintf(...)
Definition: logging.h:237
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
std::shared_ptr< CWallet > GetDefaultWallet(WalletContext &context, size_t &count)
Definition: wallet.cpp:184
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:140
static std::set< std::string > g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex)
bool IsScanning() const
Definition: wallet.h:545
Coin Control Features.
Definition: coincontrol.h:28
std::variant< TxStateConfirmed, TxStateInMempool, TxStateConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:73
An instance of this class represents one database.
Definition: db.h:124
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:841
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:62
Clock::time_point now() const
Definition: wallet.h:1072
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2845
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:129
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15