Bitcoin Core  31.0.0
P2P Digital Currency
wallet.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-present 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 <node/types.h>
16 #include <outputtype.h>
17 #include <policy/feerate.h>
18 #include <primitives/transaction.h>
20 #include <script/interpreter.h>
21 #include <script/script.h>
23 #include <sync.h>
24 #include <tinyformat.h>
25 #include <uint256.h>
26 #include <util/fs.h>
27 #include <util/hasher.h>
28 #include <util/result.h>
29 #include <util/string.h>
30 #include <util/time.h>
31 #include <util/ui_change_type.h>
32 #include <wallet/crypter.h>
33 #include <wallet/db.h>
34 #include <wallet/scriptpubkeyman.h>
35 #include <wallet/transaction.h>
36 #include <wallet/types.h>
37 #include <wallet/walletutil.h>
38 
39 #include <atomic>
40 #include <cassert>
41 #include <cstddef>
42 #include <cstdint>
43 #include <functional>
44 #include <limits>
45 #include <map>
46 #include <memory>
47 #include <optional>
48 #include <set>
49 #include <string>
50 #include <unordered_map>
51 #include <utility>
52 #include <vector>
53 
54 #include <boost/signals2/signal.hpp>
55 
56 class CKey;
57 class CKeyID;
58 class CPubKey;
59 class Coin;
60 class SigningProvider;
61 enum class MemPoolRemovalReason;
62 enum class SigningResult;
63 namespace common {
64 enum class PSBTError;
65 } // namespace common
66 namespace interfaces {
67 class Wallet;
68 }
69 namespace wallet {
70 class CWallet;
71 class WalletBatch;
72 enum class DBErrors : int;
73 } // namespace wallet
74 struct CBlockLocator;
75 struct CExtKey;
76 struct FlatSigningProvider;
77 struct KeyOriginInfo;
79 struct SignatureData;
80 
81 using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
82 
83 struct bilingual_str;
84 
85 namespace wallet {
86 struct WalletContext;
87 
90 void WaitForDeleteWallet(std::shared_ptr<CWallet>&& wallet);
91 
92 bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
93 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
94 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start);
95 std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context);
96 std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count);
97 std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name);
98 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);
99 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);
100 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, bool allow_unnamed = false);
101 std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet);
102 void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
103 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
104 
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<WalletFlags, std::string> WALLET_FLAG_TO_STRING{
163  {WALLET_FLAG_AVOID_REUSE, "avoid_reuse"},
164  {WALLET_FLAG_BLANK_WALLET, "blank"},
165  {WALLET_FLAG_KEY_ORIGIN_METADATA, "key_origin_metadata"},
166  {WALLET_FLAG_LAST_HARDENED_XPUB_CACHED, "last_hardened_xpub_cached"},
167  {WALLET_FLAG_DISABLE_PRIVATE_KEYS, "disable_private_keys"},
168  {WALLET_FLAG_DESCRIPTORS, "descriptor_wallet"},
169  {WALLET_FLAG_EXTERNAL_SIGNER, "external_signer"}
170 };
171 
172 static const std::map<std::string, WalletFlags> STRING_TO_WALLET_FLAG{
180 };
181 
198 {
199 protected:
201  const CWallet* const pwallet;
203  ScriptPubKeyMan* m_spk_man{nullptr};
206  int64_t nIndex{-1};
210  bool fInternal{false};
211 
212 public:
214  explicit ReserveDestination(CWallet* pwallet, OutputType type)
215  : pwallet(pwallet)
216  , type(type) { }
217 
218  ReserveDestination(const ReserveDestination&) = delete;
219  ReserveDestination& operator=(const ReserveDestination&) = delete;
220 
223  {
224  ReturnDestination();
225  }
226 
228  util::Result<CTxDestination> GetReservedDestination(bool internal);
230  void ReturnDestination();
232  void KeepDestination();
233 };
234 
239 {
247  std::optional<std::string> label;
248 
254  std::optional<AddressPurpose> purpose;
255 
263  bool previously_spent{false};
264 
272  std::map<std::string, std::string> receive_requests{};
273 
275  bool IsChange() const { return !label.has_value(); }
276  std::string GetLabel() const { return label ? *label : std::string{}; }
277  void SetLabel(std::string name) { label = std::move(name); }
278 };
279 
280 inline std::string PurposeToString(AddressPurpose p)
281 {
282  switch(p) {
283  case AddressPurpose::RECEIVE: return "receive";
284  case AddressPurpose::SEND: return "send";
285  case AddressPurpose::REFUND: return "refund";
286  } // no default case so the compiler will warn when a new enum as added
287  assert(false);
288 }
289 
290 inline std::optional<AddressPurpose> PurposeFromString(std::string_view s)
291 {
292  if (s == "receive") return AddressPurpose::RECEIVE;
293  else if (s == "send") return AddressPurpose::SEND;
294  else if (s == "refund") return AddressPurpose::REFUND;
295  return {};
296 }
297 
299 {
303 };
304 
305 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
310 {
311 private:
312  CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet);
313 
314  bool Unlock(const CKeyingMaterial& vMasterKeyIn);
315 
316  std::atomic<bool> fAbortRescan{false};
317  std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
318  std::atomic<bool> m_scanning_with_passphrase{false};
319  std::atomic<SteadyClock::time_point> m_scanning_start{SteadyClock::time_point{}};
320  std::atomic<double> m_scanning_progress{0};
321  friend class WalletRescanReserver;
322 
324  NodeClock::time_point m_next_resend{GetDefaultNextResend()};
327  bool fBroadcastTransactions = false;
328  // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
329  std::atomic<int64_t> m_best_block_time {0};
330 
331  // First created key time. Used to skip blocks prior to this time.
332  // 'std::numeric_limits<int64_t>::max()' if wallet is blank.
333  std::atomic<int64_t> m_birth_time{std::numeric_limits<int64_t>::max()};
334 
340  typedef std::unordered_multimap<COutPoint, Txid, SaltedOutpointHasher> TxSpends;
341  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
342  void AddToSpends(const COutPoint& outpoint, const Txid& txid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
343  void AddToSpends(const CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
344 
361  bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const SyncTxState& state, bool fUpdate, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
362 
364  void MarkConflicted(const uint256& hashBlock, int conflicting_height, const Txid& hashTx);
365 
366  enum class TxUpdate { UNCHANGED, CHANGED, NOTIFY_CHANGED };
367 
368  using TryUpdatingStateFn = std::function<TxUpdate(CWalletTx& wtx)>;
369 
371  void RecursiveUpdateTxState(const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
372  void RecursiveUpdateTxState(WalletBatch* batch, const Txid& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
373 
375  void MarkInputsDirty(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
376 
377  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
378 
379  bool SyncTransaction(const CTransactionRef& tx, const SyncTxState& state, bool update_tx = true, bool rescanning_old_block = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
380 
382  std::atomic<uint64_t> m_wallet_flags{0};
383 
384  bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& strPurpose);
385 
387  void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
388 
390  void UnsetBlankWalletFlag(WalletBatch& batch) override;
391 
394 
396  std::string m_name;
397 
399  std::unique_ptr<WalletDatabase> m_database;
400 
408  uint256 m_last_block_processed GUARDED_BY(cs_wallet);
409 
415  int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
416 
417  std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
418  std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
419 
420  // Indexed by a unique identifier produced by each ScriptPubKeyMan using
421  // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
422  std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
423 
424  // Appends spk managers into the main 'm_spk_managers'.
425  // Must be the only method adding data to it.
426  void AddScriptPubKeyMan(const uint256& id, std::unique_ptr<ScriptPubKeyMan> spkm_man);
427 
428  // Same as 'AddActiveScriptPubKeyMan' but designed for use within a batch transaction context
429  void AddActiveScriptPubKeyManWithDb(WalletBatch& batch, uint256 id, OutputType type, bool internal);
430 
432  void SetWalletFlagWithDB(WalletBatch& batch, uint64_t flags);
433 
435  std::unordered_map<CScript, std::vector<ScriptPubKeyMan*>, SaltedSipHasher> m_cached_spks;
436 
438  std::unordered_map<COutPoint, WalletTXO, SaltedOutpointHasher> m_txos GUARDED_BY(cs_wallet);
439 
445  static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings);
446 
447  static NodeClock::time_point GetDefaultNextResend();
448 
449  // Update last block processed in memory only
450  void SetLastBlockProcessedInMem(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
451 
453  void UpdateTrucSiblingConflicts(const CWalletTx& parent_wtx, const Txid& child_txid, bool add_conflict) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
454 
455 public:
461 
462  WalletDatabase& GetDatabase() const override
463  {
464  assert(static_cast<bool>(m_database));
465  return *m_database;
466  }
467 
470  const std::string& GetName() const { return m_name; }
471 
472  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
474  unsigned int nMasterKeyMaxID = 0;
475 
477  CWallet(interfaces::Chain* chain, const std::string& name, std::unique_ptr<WalletDatabase> database)
478  : m_chain(chain),
479  m_name(name),
480  m_database(std::move(database))
481  {
482  }
483 
485  {
486  // Should not have slots connected at this point.
487  assert(NotifyUnload.empty());
488  }
489 
490  bool IsLocked() const override;
491  bool Lock();
492 
494  bool HaveChain() const { return m_chain ? true : false; }
495 
498  std::unordered_map<Txid, CWalletTx, SaltedTxidHasher> mapWallet GUARDED_BY(cs_wallet);
499 
500  typedef std::multimap<int64_t, CWalletTx*> TxItems;
502 
503  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
504 
505  std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
506  const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
507 
514  std::map<COutPoint, bool> m_locked_coins GUARDED_BY(cs_wallet);
515 
517  std::unique_ptr<interfaces::Handler> m_chain_notifications_handler;
518 
520  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
521 
522  const CWalletTx* GetWalletTx(const Txid& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
523 
524  std::set<Txid> GetTxConflicts(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
525 
526  const std::unordered_map<COutPoint, WalletTXO, SaltedOutpointHasher>& GetTXOs() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return m_txos; };
527  std::optional<WalletTXO> GetTXO(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
528 
530  void RefreshTXOsFromTx(const CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
532  void RefreshAllTXOs() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
533 
547  int GetTxDepthInMainChain(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
548 
554  int GetTxBlocksToMaturity(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
555  bool IsTxImmatureCoinBase(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
556 
557  bool IsSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
558 
559  // Whether this or any known scriptPubKey with the same single key has been spent.
560  bool IsSpentKey(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
561  void SetSpentKeyState(WalletBatch& batch, const Txid& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
562 
564  util::Result<void> DisplayAddress(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
565 
566  bool IsLockedCoin(const COutPoint& output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
567  void LoadLockedCoin(const COutPoint& coin, bool persistent) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
568  bool LockCoin(const COutPoint& output, bool persist) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
569  bool UnlockCoin(const COutPoint& output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
570  bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
571  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
572 
573  /*
574  * Rescan abort properties
575  */
576  void AbortRescan() { fAbortRescan = true; }
577  bool IsAbortingRescan() const { return fAbortRescan; }
578  bool IsScanning() const { return fScanningWallet; }
579  bool IsScanningWithPassphrase() const { return m_scanning_with_passphrase; }
580  SteadyClock::duration ScanningDuration() const { return fScanningWallet ? SteadyClock::now() - m_scanning_start.load() : SteadyClock::duration{}; }
581  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
582 
584  void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
585 
587  void LoadAddressPreviouslySpent(const CTxDestination& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
589  void LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
590 
592  int64_t nRelockTime GUARDED_BY(cs_wallet){0};
593 
594  // Used to prevent concurrent calls to walletpassphrase RPC.
595  Mutex m_unlock_mutex;
596  // Used to prevent deleting the passphrase from memory when it is still in use.
598 
599  bool Unlock(const SecureString& strWalletPassphrase);
600  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
601  bool EncryptWallet(const SecureString& strWalletPassphrase);
602 
603  unsigned int ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const;
604 
609  int64_t IncOrderPosNext(WalletBatch *batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
610  DBErrors ReorderTransactions();
611 
612  void MarkDirty();
613 
620  using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
621 
626  CWalletTx* AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx=nullptr, bool rescanning_old_block = false);
627  bool LoadToWallet(const Txid& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
628  void transactionAddedToMempool(const CTransactionRef& tx) override;
629  void blockConnected(const kernel::ChainstateRole& role, const interfaces::BlockInfo& block) override;
630  void blockDisconnected(const interfaces::BlockInfo& block) override;
631  void updatedBlockTip() override;
632  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
633 
634  struct ScanResult {
635  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
636 
641  std::optional<int> last_scanned_height;
642 
648  };
649  ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, bool save_progress);
650  void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) override;
652  void SetNextResend() { m_next_resend = GetDefaultNextResend(); }
654  bool ShouldResend() const;
655  void ResubmitWalletTransactions(node::TxBroadcast broadcast_method, bool force);
656 
657  OutputType TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const;
658 
662  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const;
663  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
664 
680  std::optional<common::PSBTError> FillPSBT(PartiallySignedTransaction& psbtx,
681  bool& complete,
682  std::optional<int> sighash_type = std::nullopt,
683  bool sign = true,
684  bool bip32derivs = true,
685  size_t* n_signed = nullptr,
686  bool finalize = true) const;
687 
697  void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
698 
700  bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, node::TxBroadcast broadcast_method) const
701  EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
702 
704  void MaybeUpdateBirthTime(int64_t time);
705 
706  unsigned int m_confirm_target{DEFAULT_TX_CONFIRM_TARGET};
709  bool m_spend_zero_conf_change{DEFAULT_SPEND_ZEROCONF_CHANGE};
710  bool m_signal_rbf{DEFAULT_WALLET_RBF};
711  bool m_allow_fallback_fee{true};
719 
722  CFeeRate m_discard_rate{DEFAULT_DISCARD_FEE};
723 
728  CFeeRate m_consolidate_feerate{DEFAULT_CONSOLIDATE_FEERATE};
729 
732  OutputType m_default_address_type{DEFAULT_ADDRESS_TYPE};
739  std::optional<OutputType> m_default_change_type{};
741  CAmount m_default_max_tx_fee{DEFAULT_TRANSACTION_MAXFEE};
742 
744  int64_t m_keypool_size{DEFAULT_KEYPOOL_SIZE};
745 
748 
749  size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
750  bool TopUpKeyPool(unsigned int kpSize = 0);
751 
752  // Filter struct for 'ListAddrBookAddresses'
753  struct AddrBookFilter {
754  // Fetch addresses with the provided label
755  std::optional<std::string> m_op_label{std::nullopt};
756  // Don't include change addresses by default
757  bool ignore_change{true};
758  };
759 
763  std::vector<CTxDestination> ListAddrBookAddresses(const std::optional<AddrBookFilter>& filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
764 
768  std::set<std::string> ListAddrBookLabels(std::optional<AddressPurpose> purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
769 
774  using ListAddrBookFunc = std::function<void(const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose> purpose)>;
775  void ForEachAddrBookEntry(const ListAddrBookFunc& func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
776 
781  void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
782 
783  util::Result<CTxDestination> GetNewDestination(OutputType type, const std::string& label);
784  util::Result<CTxDestination> GetNewChangeDestination(OutputType type);
785 
786  bool IsMine(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
787  bool IsMine(const CScript& script) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
789  CAmount GetDebit(const CTxIn& txin) const;
790  bool IsMine(const CTxOut& txout) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
791  bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
792  bool IsMine(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
794  bool IsFromMe(const CTransaction& tx) const;
795  CAmount GetDebit(const CTransaction& tx) const;
796 
797  DBErrors PopulateWalletFromDB(bilingual_str& error, std::vector<bilingual_str>& warnings);
798 
800  util::Result<void> RemoveTxs(std::vector<Txid>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
801  util::Result<void> RemoveTxs(WalletBatch& batch, std::vector<Txid>& txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
802 
803  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose);
804 
805  bool DelAddressBook(const CTxDestination& address);
806  bool DelAddressBookWithDB(WalletBatch& batch, const CTxDestination& address);
807 
808  bool IsAddressPreviouslySpent(const CTxDestination& dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
809  bool SetAddressPreviouslySpent(WalletBatch& batch, const CTxDestination& dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
810 
811  std::vector<std::string> GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
812  bool SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
813  bool EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
814 
815  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
816 
818  std::set<Txid> GetConflicts(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
819 
821  bool HasWalletSpend(const CTransactionRef& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
822 
824  void Close();
825 
827  boost::signals2::signal<void ()> NotifyUnload;
828 
833  boost::signals2::signal<void(const CTxDestination& address,
834  const std::string& label, bool isMine,
835  AddressPurpose purpose, ChangeType status)>
837 
842  boost::signals2::signal<void(const Txid& hashTx, ChangeType status)> NotifyTransactionChanged;
843 
845  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
846 
848  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
849 
854  boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
855 
857  bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
859  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
860 
862  bool TransactionCanBeAbandoned(const Txid& hashTx) const;
863 
864  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
865  bool AbandonTransaction(const Txid& hashTx);
866  bool AbandonTransaction(CWalletTx& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
867 
869  bool MarkReplaced(const Txid& originalHash, const Txid& newHash);
870 
871  static bool LoadWalletArgs(std::shared_ptr<CWallet> wallet, const WalletContext& context, bilingual_str& error, std::vector<bilingual_str>& warnings);
872 
873  /* Initializes, creates and returns a new CWallet; returns a null pointer in case of an error */
874  static std::shared_ptr<CWallet> CreateNew(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bilingual_str& error, std::vector<bilingual_str>& warnings);
875 
876  /* Initializes, loads, and returns a CWallet from an existing wallet; returns a null pointer in case of an error */
877  static std::shared_ptr<CWallet> LoadExisting(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, bilingual_str& error, std::vector<bilingual_str>& warnings);
878 
883  void postInitProcess();
884 
885  bool BackupWallet(const std::string& strDest) const;
886 
887  /* Returns true if HD is enabled */
888  bool IsHDEnabled() const;
889 
890  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
891  bool CanGetAddresses(bool internal = false) const;
892 
893  /* Returns the time of the first created key or, in case of an import, it could be the time of the first received transaction */
894  int64_t GetBirthTime() const { return m_birth_time; }
895 
902  void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_wallet);
903 
905  void SetWalletFlag(uint64_t flags);
906 
908  void UnsetWalletFlag(uint64_t flag);
909 
911  bool IsWalletFlagSet(uint64_t flag) const override;
912 
916  void InitWalletFlags(uint64_t flags);
918  bool LoadWalletFlags(uint64_t flags);
920  uint64_t GetWalletFlags() const;
921 
923  std::string LogName() const override
924  {
925  std::string name{GetName()};
926  return name.empty() ? "default wallet" : name;
927  };
928 
930  std::string DisplayName() const
931  {
932  std::string name{GetName()};
933  return name.empty() ? _("default wallet") : name;
934  };
935 
937  template <typename... Params>
938  void WalletLogPrintf(util::ConstevalFormatString<sizeof...(Params)> wallet_fmt, const Params&... params) const
939  {
940  LogInfo("[%s] %s", LogName(), tfm::format(wallet_fmt, params...));
941  };
942 
943  void LogStats() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
944  {
945  AssertLockHeld(cs_wallet);
946  WalletLogPrintf("setKeyPool.size() = %u\n", GetKeyPoolSize());
947  WalletLogPrintf("mapWallet.size() = %u\n", mapWallet.size());
948  WalletLogPrintf("m_address_book.size() = %u\n", m_address_book.size());
949  };
950 
952  std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
953  bool IsActiveScriptPubKeyMan(const ScriptPubKeyMan& spkm) const;
954 
956  std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
957 
959  ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
960 
962  std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script) const;
964  ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
965 
967  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
968  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
969 
971  std::vector<WalletDescriptor> GetWalletDescriptors(const CScript& script) const;
972 
974  LegacyDataSPKM* GetLegacyDataSPKM() const;
975  LegacyDataSPKM* GetOrCreateLegacyDataSPKM();
976 
978  void SetupLegacyScriptPubKeyMan();
979 
980  bool WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const override;
981 
982  bool HasEncryptionKeys() const override;
983  bool HaveCryptedKeys() const;
984 
987  {
988  AssertLockHeld(cs_wallet);
989  assert(m_last_block_processed_height >= 0);
990  return m_last_block_processed_height;
991  };
993  {
994  AssertLockHeld(cs_wallet);
995  assert(m_last_block_processed_height >= 0);
996  return m_last_block_processed;
997  }
999  void SetLastBlockProcessed(int block_height, uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1001  void WriteBestBlock() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1002 
1004  void ConnectScriptPubKeyManNotifiers();
1005 
1007  DescriptorScriptPubKeyMan& LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor& desc);
1008 
1013  void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1014 
1019  void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1020 
1025  void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal);
1026 
1028  DescriptorScriptPubKeyMan& SetupDescriptorScriptPubKeyMan(WalletBatch& batch, const CExtKey& master_key, const OutputType& output_type, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1030  void SetupDescriptorScriptPubKeyMans(WalletBatch& batch, const CExtKey& master_key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1031  void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1032 
1034  void SetupOwnDescriptorScriptPubKeyMans(WalletBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1035 
1037  DescriptorScriptPubKeyMan* GetDescriptorScriptPubKeyMan(const WalletDescriptor& desc) const;
1038 
1042  std::optional<bool> IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const;
1043 
1045  util::Result<std::reference_wrapper<DescriptorScriptPubKeyMan>> AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1046 
1052  bool MigrateToSQLite(bilingual_str& error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1053 
1055  std::optional<MigrationData> GetDescriptorsForLegacy(bilingual_str& error) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1056 
1059  util::Result<void> ApplyMigrationData(WalletBatch& local_wallet_batch, MigrationData& data) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1060 
1062  bool CanGrindR() const;
1063 
1065  void CacheNewScriptPubKeys(const std::set<CScript>& spks, ScriptPubKeyMan* spkm);
1066 
1067  void TopUpCallback(const std::set<CScript>& spks, ScriptPubKeyMan* spkm) override;
1068 
1070  std::set<CExtPubKey> GetActiveHDPubKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
1071 
1074  std::optional<CKey> GetKey(const CKeyID& keyid) const;
1075 
1077  void DisconnectChainNotifications();
1078 };
1079 
1084 void MaybeResendWalletTxs(WalletContext& context);
1085 
1088 {
1089 private:
1090  using Clock = std::chrono::steady_clock;
1091  using NowFn = std::function<Clock::time_point()>;
1093  bool m_could_reserve{false};
1095 public:
1097 
1098  bool reserve(bool with_passphrase = false)
1099  {
1100  assert(!m_could_reserve);
1101  if (m_wallet.fScanningWallet.exchange(true)) {
1102  return false;
1103  }
1104  m_wallet.m_scanning_with_passphrase.exchange(with_passphrase);
1105  m_wallet.m_scanning_start = SteadyClock::now();
1106  m_wallet.m_scanning_progress = 0;
1107  m_could_reserve = true;
1108  return true;
1109  }
1110 
1111  bool isReserved() const
1112  {
1113  return (m_could_reserve && m_wallet.fScanningWallet);
1114  }
1115 
1116  Clock::time_point now() const { return m_now ? m_now() : Clock::now(); };
1117 
1118  void setNow(NowFn now) { m_now = std::move(now); }
1119 
1121  {
1122  if (m_could_reserve) {
1123  m_wallet.fScanningWallet = false;
1124  m_wallet.m_scanning_with_passphrase = false;
1125  }
1126  }
1127 };
1128 
1130 bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1131 
1133 bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
1134 
1136  std::string wallet_name;
1137  std::shared_ptr<CWallet> wallet;
1138  std::shared_ptr<CWallet> watchonly_wallet;
1139  std::shared_ptr<CWallet> solvables_wallet;
1141 };
1142 
1144 [[nodiscard]] util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context);
1146 [[nodiscard]] util::Result<MigrationResult> MigrateLegacyToDescriptor(std::shared_ptr<CWallet> local_wallet, const SecureString& passphrase, WalletContext& context);
1147 } // namespace wallet
1148 
1149 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:647
PSBTError
Definition: types.h:17
static void NotifyTransactionChanged(WalletModel *walletmodel, const Txid &hash, ChangeType status)
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:148
TxBroadcast
How to broadcast a local transaction.
Definition: types.h:165
std::unordered_multimap< COutPoint, Txid, SaltedOutpointHasher > TxSpends
Used to keep track of spent outpoints, and detect and report conflicts (double-spends or mutated tran...
Definition: wallet.h:340
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:417
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
static const std::map< std::string, WalletFlags > STRING_TO_WALLET_FLAG
Definition: wallet.h:172
assert(!tx.IsCoinBase())
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:81
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:116
Never set in current code may be present in older wallet databases.
Definition: handler.h:11
std::optional< int > last_scanned_height
Definition: wallet.h:641
std::optional< AddressPurpose > purpose
Address purpose which was originally recorded for payment protocol support but now serves as a cached...
Definition: wallet.h:254
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey&#39;ed, it will be returned to the keypool...
Definition: wallet.h:222
A UTXO entry.
Definition: coins.h:34
Bilingual messages:
Definition: translation.h:24
DBErrors
Overview of wallet database classes:
Definition: walletdb.h:43
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:640
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:167
std::string GetLabel() const
Definition: wallet.h:276
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:747
std::optional< AddressPurpose > PurposeFromString(std::string_view s)
Definition: wallet.h:290
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:470
static void NotifyAddressBookChanged(WalletModel *walletmodel, const CTxDestination &address, const std::string &label, bool isMine, wallet::AddressPurpose purpose, ChangeType status)
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:364
Definition: key.h:231
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:859
struct containing information needed for migrating legacy wallets to descriptor wallets ...
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:525
Result CommitTransaction(CWallet &wallet, const Txid &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, Txid &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:350
void setNow(NowFn now)
Definition: wallet.h:1118
WalletRescanReserver(CWallet &w)
Definition: wallet.h:1096
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:53
MasterKeyMap mapMasterKeys
Definition: wallet.h:473
WalletDatabase & GetDatabase() const override
Definition: wallet.h:462
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
std::string PurposeToString(AddressPurpose p)
Definition: wallet.h:280
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:201
CTxDestination address
The destination.
Definition: wallet.h:208
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:460
void LogStats() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:943
std::string DisplayName() const
Return wallet name for display, like LogName() but translates "default wallet" string.
Definition: wallet.h:930
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:109
Definition: common.h:29
std::variant< TxStateConfirmed, TxStateInMempool, TxStateInactive > SyncTxState
Subset of states transaction sync logic is implemented to handle.
Definition: transaction.h:82
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:134
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1087
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:500
A version of CTransaction with the PSBT format.
Definition: psbt.h:1138
bool reserve(bool with_passphrase=false)
Definition: wallet.h:1098
SigningResult
Definition: signmessage.h:43
Access to the wallet database.
Definition: walletdb.h:192
RecursiveMutex m_relock_mutex
Definition: wallet.h:597
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:581
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:774
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
OutputType
Definition: outputtype.h:18
std::function< Clock::time_point()> NowFn
Definition: wallet.h:1091
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:50
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
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:2142
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:422
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:437
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:194
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:393
std::function< TxUpdate(CWalletTx &wtx)> TryUpdatingStateFn
Definition: wallet.h:368
CWallet(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:477
AddressPurpose
Address purpose field that has been been stored with wallet sending and receiving addresses since BIP...
Definition: types.h:28
Indicates that the wallet needs an external signer.
Definition: walletutil.h:56
static void NotifyCanGetAddressesChanged(WalletModel *walletmodel)
bool fSubtractFeeFromAmount
Definition: wallet.h:302
void WaitForDeleteWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly delete the wallet.
Definition: wallet.cpp:254
std::shared_ptr< CWallet > wallet
Definition: wallet.h:1137
std::string wallet_name
Definition: wallet.h:1136
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:1090
An input of a transaction.
Definition: transaction.h:61
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:986
const char * name
Definition: rest.cpp:48
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:418
static const std::map< WalletFlags, std::string > WALLET_FLAG_TO_STRING
Definition: wallet.h:162
#define LogInfo(...)
Definition: log.h:95
void Unlock(Lock &lock, Callback &&callback)
Definition: util.h:207
std::optional< std::string > label
Address label which is always nullopt for change addresses.
Definition: wallet.h:247
Chain notifications.
Definition: chain.h:305
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:938
An encapsulated public key.
Definition: pubkey.h:33
std::variant< TxStateConfirmed, TxStateInMempool, TxStateBlockConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:79
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:223
CTxDestination dest
Definition: wallet.h:300
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:53
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:309
An output of a transaction.
Definition: transaction.h:139
static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress, bool resume_possible)
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:472
std::string m_name
Wallet name: relative directory name or "" for default wallet.
Definition: wallet.h:396
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
A wrapper for a compile-time partially validated format string.
Definition: base.h:41
const std::unordered_map< COutPoint, WalletTXO, SaltedOutpointHasher > & GetTXOs() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:526
TxItems wtxOrdered
Definition: wallet.h:501
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:4250
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:96
std::shared_ptr< CWallet > solvables_wallet
Definition: wallet.h:1139
Descriptor with some wallet metadata.
Definition: walletutil.h:63
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:133
Definition: init.cpp:17
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:163
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:435
int flags
Definition: bitcoin-tx.cpp:529
std::shared_ptr< CWallet > GetWallet(WalletContext &context, const std::string &name)
Definition: wallet.cpp:207
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:106
DatabaseStatus
Definition: db.h:186
static void NotifyUnload(WalletModel *walletModel)
256-bit opaque blob.
Definition: uint256.h:195
bool IsChange() const
Accessor methods.
Definition: wallet.h:275
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:194
An interface to be implemented by keystores that support signing.
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:50
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:117
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:620
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
std::shared_ptr< CWallet > watchonly_wallet
Definition: wallet.h:1138
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
int64_t GetBirthTime() const
Definition: wallet.h:894
bool IsAbortingRescan() const
Definition: wallet.h:577
CAmount nAmount
Definition: wallet.h:301
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
Address book data.
Definition: wallet.h:238
OutputType const type
Definition: wallet.h:204
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:216
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:197
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:494
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac...
Definition: feerate.h:31
void SetLabel(std::string name)
Definition: wallet.h:277
static int count
bool IsScanningWithPassphrase() const
Definition: wallet.h:579
SteadyClock::duration ScanningDuration() const
Definition: wallet.h:580
A mutable version of CTransaction.
Definition: transaction.h:357
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:992
void SetNextResend()
Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average...
Definition: wallet.h:652
std::unique_ptr< WalletDatabase > m_database
Internal database handle.
Definition: wallet.h:399
An encapsulated private key.
Definition: key.h:35
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:280
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:377
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
Definition: wallet.h:214
ChangeType
General change type (added, updated, removed).
Definition: ui_change_type.h:9
is a home for public enum and struct type definitions that are used internally by node code...
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
std::shared_ptr< CWallet > GetDefaultWallet(WalletContext &context, size_t &count)
Definition: wallet.cpp:200
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:151
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, bool allow_unnamed)
Definition: wallet.cpp:472
static std::set< std::string > g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex)
bool IsScanning() const
Definition: wallet.h:578
Coin Control Features.
Definition: coincontrol.h:83
An instance of this class represents one database.
Definition: db.h:129
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:63
Clock::time_point now() const
Definition: wallet.h:1116
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2940
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