Bitcoin Core  24.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-2021 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 <consensus/amount.h>
10 #include <fs.h>
11 #include <interfaces/chain.h>
12 #include <interfaces/handler.h>
13 #include <outputtype.h>
14 #include <policy/feerate.h>
15 #include <psbt.h>
16 #include <tinyformat.h>
17 #include <util/hasher.h>
18 #include <util/message.h>
19 #include <util/result.h>
20 #include <util/strencodings.h>
21 #include <util/string.h>
22 #include <util/system.h>
23 #include <util/ui_change_type.h>
24 #include <validationinterface.h>
25 #include <wallet/crypter.h>
26 #include <wallet/scriptpubkeyman.h>
27 #include <wallet/transaction.h>
28 #include <wallet/walletdb.h>
29 #include <wallet/walletutil.h>
30 
31 #include <algorithm>
32 #include <atomic>
33 #include <map>
34 #include <memory>
35 #include <optional>
36 #include <set>
37 #include <stdexcept>
38 #include <stdint.h>
39 #include <string>
40 #include <utility>
41 #include <unordered_map>
42 #include <vector>
43 
44 #include <boost/signals2/signal.hpp>
45 
46 
47 using LoadWalletFn = std::function<void(std::unique_ptr<interfaces::Wallet> wallet)>;
48 
49 class CScript;
50 enum class FeeEstimateMode;
51 struct bilingual_str;
52 
53 namespace wallet {
54 struct WalletContext;
55 
61 void UnloadWallet(std::shared_ptr<CWallet>&& wallet);
62 
63 bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
64 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings);
65 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start);
66 std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context);
67 std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count);
68 std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name);
69 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);
70 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);
71 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);
72 std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet);
73 void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet);
74 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);
75 
79 static const CAmount DEFAULT_FALLBACK_FEE = 0;
81 static const CAmount DEFAULT_DISCARD_FEE = 10000;
83 static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
85 static const CAmount DEFAULT_CONSOLIDATE_FEERATE{10000}; // 10 sat/vbyte
95 constexpr CAmount HIGH_APS_FEE{COIN / 10000};
99 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
101 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS{true};
103 static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 6;
105 static const bool DEFAULT_WALLET_RBF = true;
106 static const bool DEFAULT_WALLETBROADCAST = true;
107 static const bool DEFAULT_DISABLE_WALLET = false;
108 static const bool DEFAULT_WALLETCROSSCHAIN = false;
112 constexpr CAmount HIGH_TX_FEE_PER_KB{COIN / 100};
116 static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE = 91;
117 
118 class CCoinControl;
119 class CWalletTx;
120 class ReserveDestination;
121 
124 
125 static constexpr uint64_t KNOWN_WALLET_FLAGS =
133 
134 static constexpr uint64_t MUTABLE_WALLET_FLAGS =
136 
137 static const std::map<std::string,WalletFlags> WALLET_FLAG_MAP{
138  {"avoid_reuse", WALLET_FLAG_AVOID_REUSE},
139  {"blank", WALLET_FLAG_BLANK_WALLET},
140  {"key_origin_metadata", WALLET_FLAG_KEY_ORIGIN_METADATA},
141  {"last_hardened_xpub_cached", WALLET_FLAG_LAST_HARDENED_XPUB_CACHED},
142  {"disable_private_keys", WALLET_FLAG_DISABLE_PRIVATE_KEYS},
143  {"descriptor_wallet", WALLET_FLAG_DESCRIPTORS},
144  {"external_signer", WALLET_FLAG_EXTERNAL_SIGNER}
145 };
146 
147 extern const std::map<uint64_t,std::string> WALLET_FLAG_CAVEATS;
148 
165 {
166 protected:
168  const CWallet* const pwallet;
173  int64_t nIndex{-1};
177  bool fInternal{false};
178 
179 public:
182  : pwallet(pwallet)
183  , type(type) { }
184 
185  ReserveDestination(const ReserveDestination&) = delete;
187 
190  {
192  }
193 
197  void ReturnDestination();
199  void KeepDestination();
200 };
201 
204 {
205 private:
206  bool m_change{true};
207  std::string m_label;
208 public:
209  std::string purpose;
210 
211  CAddressBookData() : purpose("unknown") {}
212 
213  typedef std::map<std::string, std::string> StringMap;
215 
216  bool IsChange() const { return m_change; }
217  const std::string& GetLabel() const { return m_label; }
218  void SetLabel(const std::string& label) {
219  m_change = false;
220  m_label = label;
221  }
222 };
223 
225 {
229 };
230 
231 class WalletRescanReserver; //forward declarations for ScanForWalletTransactions/RescanFromTime
236 {
237 private:
239 
240  bool Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys = false);
241 
242  std::atomic<bool> fAbortRescan{false};
243  std::atomic<bool> fScanningWallet{false}; // controlled by WalletRescanReserver
244  std::atomic<bool> m_attaching_chain{false};
245  std::atomic<int64_t> m_scanning_start{0};
246  std::atomic<double> m_scanning_progress{0};
247  friend class WalletRescanReserver;
248 
250  int nWalletVersion GUARDED_BY(cs_wallet){FEATURE_BASE};
251 
257  // Local time that the tip block was received. Used to schedule wallet rebroadcasts.
258  std::atomic<int64_t> m_best_block_time {0};
259 
265  typedef std::unordered_multimap<COutPoint, uint256, SaltedOutpointHasher> TxSpends;
266  TxSpends mapTxSpends GUARDED_BY(cs_wallet);
267  void AddToSpends(const COutPoint& outpoint, const uint256& wtxid, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
268  void AddToSpends(const CWalletTx& wtx, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
269 
286  bool AddToWalletIfInvolvingMe(const CTransactionRef& tx, const SyncTxState& state, bool fUpdate, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
287 
289  void MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx);
290 
293 
294  void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
295 
296  void SyncTransaction(const CTransactionRef& tx, const SyncTxState& state, bool update_tx = true, bool rescanning_old_block = false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
297 
299  std::atomic<uint64_t> m_wallet_flags{0};
300 
301  bool SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::string& strPurpose);
302 
304  void UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag);
305 
307  void UnsetBlankWalletFlag(WalletBatch& batch) override;
308 
311 
314 
316  std::string m_name;
317 
319  std::unique_ptr<WalletDatabase> m_database;
320 
328  uint256 m_last_block_processed GUARDED_BY(cs_wallet);
329 
335  int m_last_block_processed_height GUARDED_BY(cs_wallet) = -1;
336 
337  std::map<OutputType, ScriptPubKeyMan*> m_external_spk_managers;
338  std::map<OutputType, ScriptPubKeyMan*> m_internal_spk_managers;
339 
340  // Indexed by a unique identifier produced by each ScriptPubKeyMan using
341  // ScriptPubKeyMan::GetID. In many cases it will be the hash of an internal structure
342  std::map<uint256, std::unique_ptr<ScriptPubKeyMan>> m_spk_managers;
343 
349  static bool AttachChain(const std::shared_ptr<CWallet>& wallet, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings);
350 
351  static int64_t GetDefaultNextResend();
352 
353 public:
359 
360  WalletDatabase& GetDatabase() const override
361  {
362  assert(static_cast<bool>(m_database));
363  return *m_database;
364  }
365 
368  const std::string& GetName() const { return m_name; }
369 
370  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
372  unsigned int nMasterKeyMaxID = 0;
373 
375  CWallet(interfaces::Chain* chain, const std::string& name, const ArgsManager& args, std::unique_ptr<WalletDatabase> database)
376  : m_args(args),
377  m_chain(chain),
378  m_name(name),
379  m_database(std::move(database))
380  {
381  }
382 
384  {
385  // Should not have slots connected at this point.
386  assert(NotifyUnload.empty());
387  }
388 
389  bool IsCrypted() const;
390  bool IsLocked() const override;
391  bool Lock();
392 
394  bool HaveChain() const { return m_chain ? true : false; }
395 
398  std::unordered_map<uint256, CWalletTx, SaltedTxidHasher> mapWallet GUARDED_BY(cs_wallet);
399 
400  typedef std::multimap<int64_t, CWalletTx*> TxItems;
402 
403  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
405 
406  std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
407  const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
408 
413  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
414 
417 
419  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
420 
422 
423  std::set<uint256> GetTxConflicts(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
424 
433  {
435  return GetTxDepthInMainChain(wtx) > 0;
436  }
437 
445 
447  bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return IsFeatureSupported(nWalletVersion, wf); }
448 
449  bool IsSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
450 
451  // Whether this or any known scriptPubKey with the same single key has been spent.
452  bool IsSpentKey(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
453  void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
454 
457 
458  bool IsLockedCoin(const COutPoint& output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
459  bool LockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
460  bool UnlockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
462  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
463 
464  /*
465  * Rescan abort properties
466  */
467  void AbortRescan() { fAbortRescan = true; }
468  bool IsAbortingRescan() const { return fAbortRescan; }
469  bool IsScanning() const { return fScanningWallet; }
470  int64_t ScanningDuration() const { return fScanningWallet ? GetTimeMillis() - m_scanning_start : 0; }
471  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
472 
475 
478 
479  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; return true; }
480 
482  void LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
483 
485  int64_t nRelockTime GUARDED_BY(cs_wallet){0};
486 
487  // Used to prevent concurrent calls to walletpassphrase RPC.
489  bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
490  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
491  bool EncryptWallet(const SecureString& strWalletPassphrase);
492 
493  void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
494  unsigned int ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const;
495 
502 
503  void MarkDirty();
504 
511  using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
512 
517  CWalletTx* AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true, bool rescanning_old_block = false);
518  bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
519  void transactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) override;
520  void blockConnected(const interfaces::BlockInfo& block) override;
521  void blockDisconnected(const interfaces::BlockInfo& block) override;
522  void updatedBlockTip() override;
523  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
524 
525  struct ScanResult {
526  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
527 
532  std::optional<int> last_scanned_height;
533 
539  };
540  ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, const bool save_progress);
541  void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override;
545  bool ShouldResend() const;
546  void ResubmitWalletTransactions(bool relay, bool force);
547 
548  OutputType TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const;
549 
553  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const;
554  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
555 
572  bool& complete,
573  int sighash_type = SIGHASH_DEFAULT,
574  bool sign = true,
575  bool bip32derivs = true,
576  size_t* n_signed = nullptr,
577  bool finalize = true) const;
578 
588  void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
589 
591  bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, bool relay) const
593 
594  bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, const CCoinControl* coin_control = nullptr) const
595  {
596  std::vector<CTxOut> v_txouts(txouts.size());
597  std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
598  return DummySignTx(txNew, v_txouts, coin_control);
599  }
600  bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, const CCoinControl* coin_control = nullptr) const;
601 
602  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
603  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
604  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);
605  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);
606 
613  bool m_allow_fallback_fee{true};
615 
621 
625 
631 
641  std::optional<OutputType> m_default_change_type{};
644 
646  bool TopUpKeyPool(unsigned int kpSize = 0);
647 
648  std::optional<int64_t> GetOldestKeyPoolTime() const;
649 
650  // Filter struct for 'ListAddrBookAddresses'
651  struct AddrBookFilter {
652  // Fetch addresses with the provided label
653  std::optional<std::string> m_op_label{std::nullopt};
654  // Don't include change addresses by default
655  bool ignore_change{true};
656  };
657 
661  std::vector<CTxDestination> ListAddrBookAddresses(const std::optional<AddrBookFilter>& filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
662 
666  std::set<std::string> ListAddrBookLabels(const std::string& purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
667 
672  using ListAddrBookFunc = std::function<void(const CTxDestination& dest, const std::string& label, const std::string& purpose, bool is_change)>;
674 
679  void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
680 
681  util::Result<CTxDestination> GetNewDestination(const OutputType type, const std::string label);
683 
690  CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
692  bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
695  bool IsFromMe(const CTransaction& tx) const;
696  CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
697  void chainStateFlushed(const CBlockLocator& loc) override;
698 
700  DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
701 
702  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
703 
704  bool DelAddressBook(const CTxDestination& address);
705 
707  bool SetAddressUsed(WalletBatch& batch, const CTxDestination& dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
708 
709  std::vector<std::string> GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
710  bool SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
711 
712  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
713 
715  void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr) override;
716 
718  int GetVersion() const { LOCK(cs_wallet); return nWalletVersion; }
719 
721  std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
722 
725 
727  void Flush();
728 
730  void Close();
731 
733  boost::signals2::signal<void ()> NotifyUnload;
734 
739  boost::signals2::signal<void(const CTxDestination& address,
740  const std::string& label, bool isMine,
741  const std::string& purpose, ChangeType status)>
743 
748  boost::signals2::signal<void(const uint256& hashTx, ChangeType status)> NotifyTransactionChanged;
749 
751  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
752 
754  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
755 
757  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
758 
763  boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
764 
768  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
769 
771  bool TransactionCanBeAbandoned(const uint256& hashTx) const;
772 
773  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
774  bool AbandonTransaction(const uint256& hashTx);
775 
777  bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
778 
779  /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
780  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);
781 
786  void postInitProcess();
787 
788  bool BackupWallet(const std::string& strDest) const;
789 
790  /* Returns true if HD is enabled */
791  bool IsHDEnabled() const;
792 
793  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
794  bool CanGetAddresses(bool internal = false) const;
795 
802  void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_wallet);
803 
805  void SetWalletFlag(uint64_t flags);
806 
808  void UnsetWalletFlag(uint64_t flag);
809 
811  bool IsWalletFlagSet(uint64_t flag) const override;
812 
816  void InitWalletFlags(uint64_t flags);
818  bool LoadWalletFlags(uint64_t flags);
819 
821  bool IsLegacy() const;
822 
824  const std::string GetDisplayName() const override {
825  std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
826  return strprintf("[%s]", wallet_name);
827  };
828 
830  template<typename... Params>
831  void WalletLogPrintf(std::string fmt, Params... parameters) const {
832  LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
833  };
834 
836  bool UpgradeWallet(int version, bilingual_str& error);
837 
839  std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
840 
842  std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
843 
845  ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
846 
848  std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script) const;
850  ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
851 
853  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
854  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
855 
857  std::vector<WalletDescriptor> GetWalletDescriptors(const CScript& script) const;
858 
862 
865 
866  const CKeyingMaterial& GetEncryptionKey() const override;
867  bool HasEncryptionKeys() const override;
868 
871  {
873  assert(m_last_block_processed_height >= 0);
874  return m_last_block_processed_height;
875  };
877  {
879  assert(m_last_block_processed_height >= 0);
880  return m_last_block_processed;
881  }
884  {
886  m_last_block_processed_height = block_height;
887  m_last_block_processed = block_hash;
888  };
889 
892 
895 
900  void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
901 
906  void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
907 
912  void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal);
913 
917 
920 
924  std::optional<bool> IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const;
925 
927  ScriptPubKeyMan* AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
928 
935 
938 
942 };
943 
949 
952 {
953 private:
954  using Clock = std::chrono::steady_clock;
955  using NowFn = std::function<Clock::time_point()>;
959 public:
960  explicit WalletRescanReserver(CWallet& w) : m_wallet(w), m_could_reserve(false) {}
961 
962  bool reserve()
963  {
964  assert(!m_could_reserve);
965  if (m_wallet.fScanningWallet.exchange(true)) {
966  return false;
967  }
968  m_wallet.m_scanning_start = GetTimeMillis();
969  m_wallet.m_scanning_progress = 0;
970  m_could_reserve = true;
971  return true;
972  }
973 
974  bool isReserved() const
975  {
976  return (m_could_reserve && m_wallet.fScanningWallet);
977  }
978 
979  Clock::time_point now() const { return m_now ? m_now() : Clock::now(); };
980 
981  void setNow(NowFn now) { m_now = std::move(now); }
982 
984  {
985  if (m_could_reserve) {
986  m_wallet.fScanningWallet = false;
987  }
988  }
989 };
990 
992 bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
993 
995 bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
996 
997 bool DummySignInput(const SigningProvider& provider, CTxIn &tx_in, const CTxOut &txout, const CCoinControl* coin_control = nullptr);
998 
999 bool FillInputToWeight(CTxIn& txin, int64_t target_weight);
1000 
1002  std::string wallet_name;
1003  std::shared_ptr<CWallet> watchonly_wallet;
1004  std::shared_ptr<CWallet> solvables_wallet;
1006 };
1007 
1009 util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context);
1010 } // namespace wallet
1011 
1012 #endif // BITCOIN_WALLET_WALLET_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:414
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:538
void ReturnDestination()
Return reserved address.
Definition: wallet.cpp:2505
void SyncTransaction(const CTransactionRef &tx, const SyncTxState &state, bool update_tx=true, bool rescanning_old_block=false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1288
bool UpgradeWallet(int version, bilingual_str &error)
Upgrade the wallet.
Definition: wallet.cpp:3181
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:123
bool m_spend_zero_conf_change
Allow Coin Selection to pick unconfirmed UTXOs that were sent from our own wallet if it cannot fund t...
Definition: wallet.h:611
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:670
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we support the named feature
Definition: wallet.h:447
std::atomic< bool > fAbortRescan
Definition: wallet.h:242
std::vector< CTxDestination > ListAddrBookAddresses(const std::optional< AddrBookFilter > &filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Filter and retrieve destinations stored in the addressbook.
Definition: wallet.cpp:2446
CFeeRate m_fallback_fee
If fee estimation does not have enough data to provide estimates, use this fee instead.
Definition: wallet.h:620
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:419
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:83
AssertLockHeld(pool.cs)
bool CanGetAddresses(bool internal=false) const
Definition: wallet.cpp:1480
int64_t nIndex
The index of the address&#39;s key in the keypool.
Definition: wallet.h:173
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:337
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:112
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:116
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::string &strPurpose)
Definition: wallet.cpp:2288
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1642
bool HasEncryptionKeys() const override
Definition: wallet.cpp:3440
assert(!tx.IsCoinBase())
std::atomic< bool > fScanningWallet
Definition: wallet.h:243
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:47
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:120
const CAddressBookData * FindAddressBookEntry(const CTxDestination &, bool allow_change=false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3171
bool SubmitTxMemoryPoolAndRelay(CWalletTx &wtx, std::string &err_string, bool relay) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Pass this transaction to node for mempool insertion and relay to peers if flag set to true...
Definition: wallet.cpp:1867
std::optional< int > last_scanned_height
Definition: wallet.h:532
int GetTxBlocksToMaturity(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3256
void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade DescriptorCaches.
Definition: wallet.cpp:453
bool LoadToWallet(const uint256 &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1056
const ArgsManager & m_args
Provider of aplication-wide arguments.
Definition: wallet.h:310
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey&#39;ed, it will be returned to the keypool...
Definition: wallet.h:189
isminetype IsMine(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1414
Bilingual messages:
Definition: translation.h:18
std::set< uint256 > GetConflicts(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get wallet transactions that conflict with given transaction (spend same outputs) ...
Definition: wallet.cpp:565
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:107
std::map< std::string, std::string > StringMap
Definition: wallet.h:213
boost::signals2::signal< void(const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:742
int64_t IncOrderPosNext(WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Increment the next transaction order id.
Definition: wallet.cpp:855
bool ApplyMigrationData(MigrationData &data, bilingual_str &error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds the ScriptPubKeyMans given in MigrationData to this wallet, removes LegacyScriptPubKeyMan, and where needed, moves tx and address book entries to watchonly_wallet or solvable_wallet.
Definition: wallet.cpp:3776
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:531
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:111
std::string m_label
Definition: wallet.h:207
void SetLabel(const std::string &label)
Definition: wallet.h:218
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, const CCoinControl *coin_control=nullptr) const
Definition: wallet.h:594
bool SetAddressReceiveRequest(WalletBatch &batch, const CTxDestination &dest, const std::string &id, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2762
bool MigrateToSQLite(bilingual_str &error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Move all records from the BDB database to a new SQLite database for storage.
Definition: wallet.cpp:3686
SigningResult
Definition: message.h:43
CWalletTx * AddToWallet(CTransactionRef tx, const TxState &state, const UpdateWalletTxFn &update_wtx=nullptr, bool fFlushOnClose=true, bool rescanning_old_block=false)
Add the transaction to the wallet, wrapping it up inside a CWalletTx.
Definition: wallet.cpp:958
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)
Definition: wallet.cpp:1672
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:368
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:267
Definition: key.h:161
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:768
struct containing information needed for migrating legacy wallets to descriptor wallets ...
Definition: walletutil.h:112
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:521
void setNow(NowFn now)
Definition: wallet.h:981
void blockConnected(const interfaces::BlockInfo &block) override
Definition: wallet.cpp:1346
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:3582
WalletRescanReserver(CWallet &w)
Definition: wallet.h:960
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:59
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2257
MasterKeyMap mapMasterKeys
Definition: wallet.h:371
WalletDatabase & GetDatabase() const override
Definition: wallet.h:360
static unsigned const char sighash[]
Definition: sighash.json.h:2
void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence) override
Definition: wallet.cpp:1299
bool fInternal
Whether this is from the internal (change output) keypool.
Definition: wallet.h:177
std::optional< int64_t > GetOldestKeyPoolTime() const
Definition: wallet.cpp:2409
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:168
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:52
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Definition: wallet.cpp:2117
void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Remove specified ScriptPubKeyMan from set of active SPK managers.
Definition: wallet.cpp:3565
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:2314
CTxDestination address
The destination.
Definition: wallet.h:175
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:358
bool SignTransaction(CMutableTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Fetch the inputs and sign with SIGHASH_ALL.
Definition: wallet.cpp:2002
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:71
std::string purpose
Definition: wallet.h:209
std::variant< TxStateConfirmed, TxStateInMempool, TxStateInactive > SyncTxState
Subset of states transaction sync logic is implemented to handle.
Definition: transaction.h:69
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:107
CAmount m_max_aps_fee
The maximum fee amount we&#39;re willing to pay to prioritize partial spend avoidance.
Definition: wallet.h:633
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:951
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:349
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:400
std::unique_ptr< interfaces::Handler > m_chain_notifications_handler
Registered interfaces::Chain::Notifications handler.
Definition: wallet.h:416
A version of CTransaction with the PSBT format.
Definition: psbt.h:946
std::vector< std::string > GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2748
const CWalletTx * GetWalletTx(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:429
Access to the wallet database.
Definition: walletdb.h:187
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:3345
std::atomic< uint64_t > m_wallet_flags
WalletFlags set on this wallet.
Definition: wallet.h:299
boost::signals2::signal< void()> NotifyUnload
Wallet is about to be unloaded.
Definition: wallet.h:733
boost::signals2::signal< void(const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:748
CFeeRate m_consolidate_feerate
When the actual feerate is less than the consolidate feerate, we will tend to make transactions which...
Definition: wallet.h:630
bool fBroadcastTransactions
Whether this wallet will submit newly created transactions to the node&#39;s mempool and prompt rebroadca...
Definition: wallet.h:256
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, const SyncTxState &state, bool fUpdate, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:1100
double ScanningProgress() const
Definition: wallet.h:471
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:33
uint64_t nAccountingEntryNumber
Definition: wallet.h:404
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:3403
bool isReserved() const
Definition: wallet.h:974
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2578
bool IsAddressUsed(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2733
std::set< ScriptPubKeyMan * > GetAllScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans.
Definition: wallet.cpp:3336
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:696
OutputType
Definition: outputtype.h:17
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:479
static int64_t GetDefaultNextResend()
Definition: wallet.cpp:1924
std::function< Clock::time_point()> NowFn
Definition: wallet.h:955
ArgsManager args
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:63
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:114
void updatedBlockTip() override
Definition: wallet.cpp:1375
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:134
std::optional< bool > IsInternalScriptPubKeyMan(ScriptPubKeyMan *spk_man) const
Returns whether the provided ScriptPubKeyMan is internal.
Definition: wallet.cpp:3604
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:610
bool LockCoin(const COutPoint &output, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2528
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:105
void MaybeResendWalletTxs(WalletContext &context)
Called periodically by the schedule thread.
Definition: wallet.cpp:1987
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:93
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:99
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:342
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:754
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
bool DisplayAddress(const CTxDestination &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Display address on an external signer.
Definition: wallet.cpp:2514
bool HasWalletSpend(const CTransactionRef &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Check if a given transaction has any of its outputs spent by another transaction in the wallet...
Definition: wallet.cpp:588
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:3453
constexpr CAmount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:77
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:137
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:313
bool FillInputToWeight(CTxIn &txin, int64_t target_weight)
Definition: wallet.cpp:1571
DescriptorScriptPubKeyMan * GetDescriptorScriptPubKeyMan(const WalletDescriptor &desc) const
Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet...
Definition: wallet.cpp:3591
bool IsLocked() const override
Definition: wallet.cpp:3281
Indicates that the wallet needs an external signer.
Definition: walletutil.h:69
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:3421
std::optional< OutputType > m_default_change_type
Default output type for change outputs.
Definition: wallet.h:641
bool MarkReplaced(const uint256 &originalHash, const uint256 &newHash)
Mark a transaction as replaced by another transaction.
Definition: wallet.cpp:876
bool fSubtractFeeFromAmount
Definition: wallet.h:228
std::underlying_type< isminetype >::type isminefilter
used for bitflags of isminetype
Definition: wallet.h:41
void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Adds the active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3536
bool ShouldResend() const
Return true if all conditions for periodically resending transactions are met.
Definition: wallet.cpp:1907
std::set< ScriptPubKeyMan * > GetActiveScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers.
Definition: wallet.cpp:3322
std::string wallet_name
Definition: wallet.h:1002
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for replacement txs
Definition: wallet.h:97
std::chrono::steady_clock Clock
Definition: wallet.h:954
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:766
An input of a transaction.
Definition: transaction.h:73
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:125
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:870
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr) override
signify that a particular wallet feature is now used.
Definition: wallet.cpp:548
#define LOCK(cs)
Definition: sync.h:261
const char * name
Definition: rest.cpp:46
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:103
void MarkInputsDirty(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Mark a transaction&#39;s inputs dirty, thus forcing the outputs to be recomputed.
Definition: wallet.cpp:1173
void Flush()
Flush wallet (bitdb flush)
Definition: wallet.cpp:600
void AbortRescan()
Definition: wallet.h:467
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:338
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:491
void chainStateFlushed(const CBlockLocator &loc) override
Definition: wallet.cpp:537
util::Result< CTxDestination > GetReservedDestination(bool internal)
Reserve an address.
Definition: wallet.cpp:2476
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:883
CFeeRate m_pay_tx_fee
Definition: wallet.h:607
void blockDisconnected(const interfaces::BlockInfo &block) override
Definition: wallet.cpp:1359
Chain notifications.
Definition: chain.h:259
int nWalletVersion GUARDED_BY(cs_wallet)
the current wallet version: clients below this version are not able to load the wallet ...
Definition: wallet.h:250
CAmount m_default_max_tx_fee
Absolute maximum transaction fee (in satoshis) used by default for the wallet.
Definition: wallet.h:643
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: ismine.h:41
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1452
static const CAmount DEFAULT_DISCARD_FEE
-discardfee default
Definition: wallet.h:81
FeeEstimateMode
Definition: feerate.h:21
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:177
int64_t m_next_resend
The next scheduled rebroadcast of wallet transactions.
Definition: wallet.h:253
bool IsFeatureSupported(int wallet_version, int feature_version)
Definition: walletutil.cpp:33
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1703
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:15
CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet)
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:66
const std::string & GetLabel() const
Definition: wallet.h:217
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1183
unsigned int ComputeTimeSmart(const CWalletTx &wtx, bool rescanning_old_block) const
Compute smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:2661
bool IsHDEnabled() const
Definition: wallet.cpp:1469
bool BackupWallet(const std::string &strDest) const
Definition: wallet.cpp:3224
WalletContext context
std::set< uint256 > GetTxConflicts(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1897
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:235
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:149
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:2308
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2360
int64_t ScanningDuration() const
Definition: wallet.h:470
An output of a transaction.
Definition: transaction.h:156
DBErrors LoadWallet()
Definition: wallet.cpp:2234
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:370
bool IsTxImmatureCoinBase(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3268
bool m_signal_rbf
Definition: wallet.h:612
bool UnlockCoin(const COutPoint &output, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2538
void MarkDirty()
Definition: wallet.cpp:867
std::string m_name
Wallet name: relative directory name or "" for default wallet.
Definition: wallet.h:316
bool IsWalletFlagSet(uint64_t flag) const override
check if a certain wallet flag is set
Definition: wallet.cpp:1520
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:34
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:137
void UnsetBlankWalletFlag(WalletBatch &batch) override
Unset the blank wallet flag and saves it to disk.
Definition: wallet.cpp:1515
bool Unlock(const CKeyingMaterial &vMasterKeyIn, bool accept_no_keys=false)
Definition: wallet.cpp:3307
TxItems wtxOrdered
Definition: wallet.h:401
ScanResult ScanForWalletTransactions(const uint256 &start_block, int start_height, std::optional< int > max_height, const WalletRescanReserver &reserver, bool fUpdate, const bool save_progress)
Scan the block chain (starting in start_block) for transactions from or to us.
Definition: wallet.cpp:1747
Definition: node.h:39
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:209
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:79
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:4060
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:751
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:60
void ForEachAddrBookEntry(const ListAddrBookFunc &func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2437
std::shared_ptr< CWallet > solvables_wallet
Definition: wallet.h:1004
bool IsTxInMainChain(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:432
ScriptPubKeyMan * m_spk_man
The ScriptPubKeyMan to reserve from. Based on type when GetReservedDestination is called...
Definition: wallet.h:170
Descriptor with some wallet metadata.
Definition: walletutil.h:76
bool SetAddressUsed(WalletBatch &batch, const CTxDestination &dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2712
void Close()
Close wallet database.
Definition: wallet.cpp:605
Address book data.
Definition: wallet.h:203
CWallet(interfaces::Chain *chain, const std::string &name, const ArgsManager &args, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:375
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:106
void postInitProcess()
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:3214
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:122
int flags
Definition: bitcoin-tx.cpp:525
std::shared_ptr< CWallet > GetWallet(WalletContext &context, const std::string &name)
Definition: wallet.cpp:161
const std::string GetDisplayName() const override
Returns a bracketed wallet name for displaying in logs, will return [default wallet] if the wallet ha...
Definition: wallet.h:824
std::atomic< int64_t > m_best_block_time
Definition: wallet.h:258
DatabaseStatus
Definition: db.h:219
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1652
256-bit opaque blob.
Definition: uint256.h:119
std::function< void(const CTxDestination &dest, const std::string &label, const std::string &purpose, bool is_change)> ListAddrBookFunc
Walk-through the address book entries.
Definition: wallet.h:672
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
void ResubmitWalletTransactions(bool relay, bool force)
Definition: wallet.cpp:1950
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:148
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1166
An interface to be implemented by keystores that support signing.
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:2371
bool IsLockedCoin(const COutPoint &output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2560
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:117
void KeepDestination()
Keep the address. Do not return it&#39;s key to the keypool when this object goes out of scope...
Definition: wallet.cpp:2496
CScript scriptPubKey
Definition: wallet.h:226
const CChainParams & Params()
Return the currently selected parameters.
bool IsSpent(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Outpoint is spent if any non-conflicted transaction spends it:
Definition: wallet.cpp:653
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Definition: wallet.h:511
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:410
bool m_allow_fallback_fee
will be false if -fallbackfee=0
Definition: wallet.h:613
void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Loads an active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3545
void InitWalletFlags(uint64_t flags)
overwrite all flags by the given uint64_t flags must be uninitialised (or 0) only known flags may be ...
Definition: wallet.cpp:1537
std::shared_ptr< CWallet > watchonly_wallet
Definition: wallet.h:1003
std::set< ScriptPubKeyMan * > GetScriptPubKeyMans(const CScript &script) const
Get all the ScriptPubKeyMans for a script.
Definition: wallet.cpp:3355
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2343
bool IsAbortingRescan() const
Definition: wallet.h:468
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:763
CAmount nAmount
Definition: wallet.h:227
bool IsCrypted() const
Definition: wallet.cpp:3276
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:121
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
unsigned int m_confirm_target
Definition: wallet.h:608
OutputType const type
Definition: wallet.h:171
void LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds a destination data tuple to the store, without saving it to disk.
Definition: wallet.cpp:2728
std::set< std::string > ListAddrBookLabels(const std::string &purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Retrieve all the known labels in the address book.
Definition: wallet.cpp:2462
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:170
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:110
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:164
DBErrors ReorderTransactions()
Definition: wallet.cpp:798
TransactionError
Definition: error.h:22
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:394
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:45
bool LoadWalletFlags(uint64_t flags)
Loads the flags into the wallet.
Definition: wallet.cpp:1525
void SetSpentKeyState(WalletBatch &batch, const uint256 &hash, unsigned int n, bool used, std::set< CTxDestination > &tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:908
static int count
Definition: tests.c:33
std::optional< MigrationData > GetDescriptorsForLegacy(bilingual_str &error) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get all of the descriptors from a legacy wallet.
Definition: wallet.cpp:3758
std::vector< WalletDescriptor > GetWalletDescriptors(const CScript &script) const
Get the wallet descriptors for a script.
Definition: wallet.cpp:3391
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:265
A mutable version of CTransaction.
Definition: transaction.h:372
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:876
void SetNextResend()
Set the next time this wallet should resend transactions to 12-36 hours from now, ~1 day on average...
Definition: wallet.h:543
bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2548
std::unique_ptr< WalletDatabase > m_database
Internal database handle.
Definition: wallet.h:319
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1501
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
Definition: wallet.cpp:438
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:718
void MarkDestinationsDirty(const std::set< CTxDestination > &destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Marks all outputs in each one of the destinations dirty, so their cache is reset and does not return ...
Definition: wallet.cpp:2423
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:287
Mutex m_unlock_mutex
Definition: wallet.h:485
static const bool DEFAULT_WALLETCROSSCHAIN
Definition: wallet.h:108
std::shared_ptr< CWallet > wallet
constexpr CAmount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:95
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Definition: wallet.h:831
OutputType m_default_address_type
Definition: wallet.h:634
static const CAmount DEFAULT_CONSOLIDATE_FEERATE
-consolidatefeerate default
Definition: wallet.h:85
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)
Definition: wallet.cpp:1662
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:280
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
Definition: wallet.h:181
ChangeType
General change type (added, updated, removed).
Definition: ui_change_type.h:9
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:385
#define LogPrintf(...)
Definition: logging.h:234
ReserveDestination & operator=(const ReserveDestination &)=delete
util::Result< CTxDestination > GetNewDestination(const OutputType type, const std::string label)
Definition: wallet.cpp:2381
unsigned int nMasterKeyMaxID
Definition: wallet.h:372
bool DummySignInput(const SigningProvider &provider, CTxIn &tx_in, const CTxOut &txout, const CCoinControl *coin_control)
Definition: wallet.cpp:1555
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
const CKeyingMaterial & GetEncryptionKey() const override
Definition: wallet.cpp:3435
std::shared_ptr< CWallet > GetDefaultWallet(WalletContext &context, size_t &count)
Definition: wallet.cpp:154
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:110
void MarkConflicted(const uint256 &hashBlock, int conflicting_height, const uint256 &hashTx)
Mark a transaction (and its in-wallet descendants) as conflicting with a particular block...
Definition: wallet.cpp:1238
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
std::atomic< double > m_scanning_progress
Definition: wallet.h:246
bool IsScanning() const
Definition: wallet.h:469
CFeeRate m_discard_rate
If the cost to spend a change output at this feerate is greater than the value of the output itself...
Definition: wallet.h:624
void ConnectScriptPubKeyManNotifiers()
Connect the signals from ScriptPubKeyMans to the signals in CWallet.
Definition: wallet.cpp:3445
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2566
CFeeRate m_min_fee
Override with -mintxfee.
Definition: wallet.h:614
Coin Control Features.
Definition: coincontrol.h:29
std::atomic< int64_t > m_scanning_start
Definition: wallet.h:245
std::variant< TxStateConfirmed, TxStateInMempool, TxStateConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:66
An instance of this class represents one database.
Definition: db.h:105
bool IsChange() const
Definition: wallet.h:216
TransactionError FillPSBT(PartiallySignedTransaction &psbtx, bool &complete, int sighash_type=SIGHASH_DEFAULT, bool sign=true, bool bip32derivs=true, size_t *n_signed=nullptr, bool finalize=true) const
Fills out a PSBT with information from the wallet.
Definition: wallet.cpp:2036
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:757
void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string >> orderForm)
Submit the transaction to the node&#39;s mempool and then relay to peers.
Definition: wallet.cpp:2193
util::Result< CTxDestination > GetNewChangeDestination(const OutputType type)
Definition: wallet.cpp:2398
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:62
void UnsetWalletFlagWithDB(WalletBatch &batch, uint64_t flag)
Unsets a wallet flag and saves it to disk.
Definition: wallet.cpp:1507
ScriptPubKeyMan * AddWalletDescriptor(WalletDescriptor &desc, const FlatSigningProvider &signing_provider, const std::string &label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Add a descriptor to the wallet, return a ScriptPubKeyMan & associated output type.
Definition: wallet.cpp:3628
Clock::time_point now() const
Definition: wallet.h:979
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2776
bool IsSpentKey(const CScript &scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:927
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)
Definition: wallet.cpp:2800
OutputType TransactionChangeType(const std::optional< OutputType > &change_type, const std::vector< CRecipient > &vecSend) const
Definition: wallet.cpp:2130
static bool AttachChain(const std::shared_ptr< CWallet > &wallet, interfaces::Chain &chain, const bool rescan_required, bilingual_str &error, std::vector< bilingual_str > &warnings)
Catch wallet up to current chain, scanning new blocks, updating the best block locator and m_last_blo...
Definition: wallet.cpp:3047
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:3415
void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3487
std::atomic< bool > m_attaching_chain
Definition: wallet.h:244
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:101
CAmount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Returns amount of debit if the input matches the filter, otherwise returns 0.
Definition: wallet.cpp:1392
void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
Definition: wallet.cpp:1309
int GetTxDepthInMainChain(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
Definition: wallet.cpp:3244
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:3375