Bitcoin Core  23.99.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 
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 
253  int64_t nNextResend = 0;
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;
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> const 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 public:
357 
358  WalletDatabase& GetDatabase() const override
359  {
360  assert(static_cast<bool>(m_database));
361  return *m_database;
362  }
363 
366  const std::string& GetName() const { return m_name; }
367 
368  typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
370  unsigned int nMasterKeyMaxID = 0;
371 
373  CWallet(interfaces::Chain* chain, const std::string& name, const ArgsManager& args, std::unique_ptr<WalletDatabase> database)
374  : m_args(args),
375  m_chain(chain),
376  m_name(name),
377  m_database(std::move(database))
378  {
379  }
380 
382  {
383  // Should not have slots connected at this point.
384  assert(NotifyUnload.empty());
385  }
386 
387  bool IsCrypted() const;
388  bool IsLocked() const override;
389  bool Lock();
390 
392  bool HaveChain() const { return m_chain ? true : false; }
393 
396  std::unordered_map<uint256, CWalletTx, SaltedTxidHasher> mapWallet GUARDED_BY(cs_wallet);
397 
398  typedef std::multimap<int64_t, CWalletTx*> TxItems;
400 
401  int64_t nOrderPosNext GUARDED_BY(cs_wallet) = 0;
403 
404  std::map<CTxDestination, CAddressBookData> m_address_book GUARDED_BY(cs_wallet);
405  const CAddressBookData* FindAddressBookEntry(const CTxDestination&, bool allow_change = false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
406 
411  std::set<COutPoint> setLockedCoins GUARDED_BY(cs_wallet);
412 
415 
417  interfaces::Chain& chain() const { assert(m_chain); return *m_chain; }
418 
420 
421  std::set<uint256> GetTxConflicts(const CWalletTx& wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
422 
431  {
433  return GetTxDepthInMainChain(wtx) > 0;
434  }
435 
443 
445  bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); return IsFeatureSupported(nWalletVersion, wf); }
446 
447  bool IsSpent(const COutPoint& outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
448 
449  // Whether this or any known scriptPubKey with the same single key has been spent.
450  bool IsSpentKey(const CScript& scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
451  void SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
452 
455 
456  bool IsLockedCoin(const COutPoint& output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
457  bool LockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
458  bool UnlockCoin(const COutPoint& output, WalletBatch* batch = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
460  void ListLockedCoins(std::vector<COutPoint>& vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
461 
462  /*
463  * Rescan abort properties
464  */
465  void AbortRescan() { fAbortRescan = true; }
466  bool IsAbortingRescan() const { return fAbortRescan; }
467  bool IsScanning() const { return fScanningWallet; }
468  int64_t ScanningDuration() const { return fScanningWallet ? GetTimeMillis() - m_scanning_start : 0; }
469  double ScanningProgress() const { return fScanningWallet ? (double) m_scanning_progress : 0; }
470 
473 
476 
477  bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; return true; }
478 
480  void LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
481 
483  int64_t nRelockTime GUARDED_BY(cs_wallet){0};
484 
485  // Used to prevent concurrent calls to walletpassphrase RPC.
487  bool Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys = false);
488  bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
489  bool EncryptWallet(const SecureString& strWalletPassphrase);
490 
491  void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
492  unsigned int ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const;
493 
500 
501  void MarkDirty();
502 
509  using UpdateWalletTxFn = std::function<bool(CWalletTx& wtx, bool new_tx)>;
510 
515  CWalletTx* AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx=nullptr, bool fFlushOnClose=true, bool rescanning_old_block = false);
516  bool LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
517  void transactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) override;
518  void blockConnected(const interfaces::BlockInfo& block) override;
519  void blockDisconnected(const interfaces::BlockInfo& block) override;
520  void updatedBlockTip() override;
521  int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update);
522 
523  struct ScanResult {
524  enum { SUCCESS, FAILURE, USER_ABORT } status = SUCCESS;
525 
530  std::optional<int> last_scanned_height;
531 
537  };
538  ScanResult ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, const bool save_progress);
539  void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override;
542 
543  OutputType TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const;
544 
548  bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const;
549  SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const;
550 
567  bool& complete,
568  int sighash_type = SIGHASH_DEFAULT,
569  bool sign = true,
570  bool bip32derivs = true,
571  size_t* n_signed = nullptr,
572  bool finalize = true) const;
573 
583  void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm);
584 
586  bool SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, bool relay) const
588 
589  bool DummySignTx(CMutableTransaction &txNew, const std::set<CTxOut> &txouts, const CCoinControl* coin_control = nullptr) const
590  {
591  std::vector<CTxOut> v_txouts(txouts.size());
592  std::copy(txouts.begin(), txouts.end(), v_txouts.begin());
593  return DummySignTx(txNew, v_txouts, coin_control);
594  }
595  bool DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, const CCoinControl* coin_control = nullptr) const;
596 
597  bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
598  bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
599  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);
600  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);
601 
608  bool m_allow_fallback_fee{true};
616 
620 
626 
636  std::optional<OutputType> m_default_change_type{};
639 
641  bool TopUpKeyPool(unsigned int kpSize = 0);
642 
643  std::optional<int64_t> GetOldestKeyPoolTime() const;
644 
645  // Filter struct for 'ListAddrBookAddresses'
646  struct AddrBookFilter {
647  // Fetch addresses with the provided label
648  std::optional<std::string> m_op_label{std::nullopt};
649  // Don't include change addresses by default
650  bool ignore_change{true};
651  };
652 
656  std::vector<CTxDestination> ListAddrBookAddresses(const std::optional<AddrBookFilter>& filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
657 
661  std::set<std::string> ListAddrBookLabels(const std::string& purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
662 
667  using ListAddrBookFunc = std::function<void(const CTxDestination& dest, const std::string& label, const std::string& purpose, bool is_change)>;
669 
674  void MarkDestinationsDirty(const std::set<CTxDestination>& destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
675 
676  util::Result<CTxDestination> GetNewDestination(const OutputType type, const std::string label);
678 
685  CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
687  bool IsMine(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
689  bool IsFromMe(const CTransaction& tx) const;
690  CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
691  void chainStateFlushed(const CBlockLocator& loc) override;
692 
694  DBErrors ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
695 
696  bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
697 
698  bool DelAddressBook(const CTxDestination& address);
699 
701  bool SetAddressUsed(WalletBatch& batch, const CTxDestination& dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
702 
703  std::vector<std::string> GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
704  bool SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
705 
706  unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
707 
709  void SetMinVersion(enum WalletFeature, WalletBatch* batch_in = nullptr) override;
710 
712  int GetVersion() const { LOCK(cs_wallet); return nWalletVersion; }
713 
715  std::set<uint256> GetConflicts(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
716 
719 
721  void Flush();
722 
724  void Close();
725 
727  boost::signals2::signal<void ()> NotifyUnload;
728 
733  boost::signals2::signal<void(const CTxDestination& address,
734  const std::string& label, bool isMine,
735  const std::string& purpose, ChangeType status)>
737 
742  boost::signals2::signal<void(const uint256& hashTx, ChangeType status)> NotifyTransactionChanged;
743 
745  boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
746 
748  boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
749 
751  boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
752 
757  boost::signals2::signal<void (CWallet* wallet)> NotifyStatusChanged;
758 
762  void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
763 
765  bool TransactionCanBeAbandoned(const uint256& hashTx) const;
766 
767  /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
768  bool AbandonTransaction(const uint256& hashTx);
769 
771  bool MarkReplaced(const uint256& originalHash, const uint256& newHash);
772 
773  /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
774  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);
775 
780  void postInitProcess();
781 
782  bool BackupWallet(const std::string& strDest) const;
783 
784  /* Returns true if HD is enabled */
785  bool IsHDEnabled() const;
786 
787  /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
788  bool CanGetAddresses(bool internal = false) const;
789 
796  void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main) EXCLUSIVE_LOCKS_REQUIRED(!cs_wallet);
797 
799  void SetWalletFlag(uint64_t flags);
800 
802  void UnsetWalletFlag(uint64_t flag);
803 
805  bool IsWalletFlagSet(uint64_t flag) const override;
806 
809  bool AddWalletFlags(uint64_t flags);
811  bool LoadWalletFlags(uint64_t flags);
812 
814  bool IsLegacy() const;
815 
817  const std::string GetDisplayName() const override {
818  std::string wallet_name = GetName().length() == 0 ? "default wallet" : GetName();
819  return strprintf("[%s]", wallet_name);
820  };
821 
823  template<typename... Params>
824  void WalletLogPrintf(std::string fmt, Params... parameters) const {
825  LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...);
826  };
827 
829  bool UpgradeWallet(int version, bilingual_str& error);
830 
832  std::set<ScriptPubKeyMan*> GetActiveScriptPubKeyMans() const;
833 
835  std::set<ScriptPubKeyMan*> GetAllScriptPubKeyMans() const;
836 
838  ScriptPubKeyMan* GetScriptPubKeyMan(const OutputType& type, bool internal) const;
839 
841  std::set<ScriptPubKeyMan*> GetScriptPubKeyMans(const CScript& script) const;
843  ScriptPubKeyMan* GetScriptPubKeyMan(const uint256& id) const;
844 
846  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const;
847  std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script, SignatureData& sigdata) const;
848 
850  std::vector<WalletDescriptor> GetWalletDescriptors(const CScript& script) const;
851 
855 
858 
859  const CKeyingMaterial& GetEncryptionKey() const override;
860  bool HasEncryptionKeys() const override;
861 
864  {
866  assert(m_last_block_processed_height >= 0);
867  return m_last_block_processed_height;
868  };
870  {
872  assert(m_last_block_processed_height >= 0);
873  return m_last_block_processed;
874  }
877  {
879  m_last_block_processed_height = block_height;
880  m_last_block_processed = block_hash;
881  };
882 
885 
888 
893  void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
894 
899  void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal);
900 
905  void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal);
906 
909 
912 
916  std::optional<bool> IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const;
917 
919  ScriptPubKeyMan* AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet);
920 };
921 
927 
930 {
931 private:
932  using Clock = std::chrono::steady_clock;
933  using NowFn = std::function<Clock::time_point()>;
937 public:
938  explicit WalletRescanReserver(CWallet& w) : m_wallet(w), m_could_reserve(false) {}
939 
940  bool reserve()
941  {
942  assert(!m_could_reserve);
943  if (m_wallet.fScanningWallet.exchange(true)) {
944  return false;
945  }
946  m_wallet.m_scanning_start = GetTimeMillis();
947  m_wallet.m_scanning_progress = 0;
948  m_could_reserve = true;
949  return true;
950  }
951 
952  bool isReserved() const
953  {
954  return (m_could_reserve && m_wallet.fScanningWallet);
955  }
956 
957  Clock::time_point now() const { return m_now ? m_now() : Clock::now(); };
958 
959  void setNow(NowFn now) { m_now = std::move(now); }
960 
962  {
963  if (m_could_reserve) {
964  m_wallet.fScanningWallet = false;
965  }
966  }
967 };
968 
970 bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
971 
973 bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name);
974 
975 bool DummySignInput(const SigningProvider& provider, CTxIn &tx_in, const CTxOut &txout, const CCoinControl* coin_control = nullptr);
976 
977 bool FillInputToWeight(CTxIn& txin, int64_t target_weight);
978 } // namespace wallet
979 
980 #endif // BITCOIN_WALLET_WALLET_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
int flags
Definition: bitcoin-tx.cpp:526
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:121
const CChainParams & Params()
Return the currently selected parameters.
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:24
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:35
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:288
An input of a transaction.
Definition: transaction.h:74
An output of a transaction.
Definition: transaction.h:157
A UTXO entry.
Definition: coins.h:31
An interface to be implemented by keystores that support signing.
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
Chain notifications.
Definition: chain.h:260
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:118
256-bit opaque blob.
Definition: uint256.h:126
Address book data.
Definition: wallet.h:204
std::map< std::string, std::string > StringMap
Definition: wallet.h:213
const std::string & GetLabel() const
Definition: wallet.h:217
std::string m_label
Definition: wallet.h:207
void SetLabel(const std::string &label)
Definition: wallet.h:218
bool IsChange() const
Definition: wallet.h:216
std::string purpose
Definition: wallet.h:209
Coin Control Features.
Definition: coincontrol.h:30
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:236
std::atomic< bool > fAbortRescan
Definition: wallet.h:242
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:366
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:392
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:760
bool m_signal_rbf
Definition: wallet.h:607
bool IsCrypted() const
Definition: wallet.cpp:3234
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:2695
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Definition: wallet.h:509
boost::signals2::signal< void()> NotifyUnload
Wallet is about to be unloaded.
Definition: wallet.h:727
CAmount m_default_max_tx_fee
Absolute maximum transaction fee (in satoshis) used by default for the wallet.
Definition: wallet.h:638
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:736
OutputType m_default_address_type
Definition: wallet.h:629
int m_last_block_processed_height GUARDED_BY(cs_wallet)
Height of last block processed is used by wallet to know depth of transactions without relying on Cha...
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:619
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:3358
void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Adds the active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3485
void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Loads an active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3494
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:3330
bool IsTxImmatureCoinBase(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3226
const CKeyingMaterial & GetEncryptionKey() const override
Definition: wallet.cpp:3390
std::set< ScriptPubKeyMan * > GetActiveScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers.
Definition: wallet.cpp:3277
const CAddressBookData * FindAddressBookEntry(const CTxDestination &, bool allow_change=false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3127
CFeeRate m_pay_tx_fee
Definition: wallet.h:602
void postInitProcess()
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:3170
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:3202
int64_t ScanningDuration() const
Definition: wallet.h:468
unsigned int nMasterKeyMaxID
Definition: wallet.h:370
bool IsScanning() const
Definition: wallet.h:467
bool SetAddressUsed(WalletBatch &batch, const CTxDestination &dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2679
std::map< CTxDestination, CAddressBookData > m_address_book GUARDED_BY(cs_wallet)
const ArgsManager & m_args
Provider of aplication-wide arguments.
Definition: wallet.h:310
bool SetAddressReceiveRequest(WalletBatch &batch, const CTxDestination &dest, const std::string &id, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2729
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:863
std::atomic< double > m_scanning_progress
Definition: wallet.h:246
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:748
CAmount m_max_aps_fee
The maximum fee amount we're willing to pay to prioritize partial spend avoidance.
Definition: wallet.h:628
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:373
WalletDatabase & GetDatabase() const override
Definition: wallet.h:358
DescriptorScriptPubKeyMan * GetDescriptorScriptPubKeyMan(const WalletDescriptor &desc) const
Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet.
Definition: wallet.cpp:3540
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:817
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:337
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:3408
uint256 m_last_block_processed GUARDED_BY(cs_wallet)
The following is used to keep track of how far behind the wallet is from the chain sync,...
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:3531
CKeyingMaterial vMasterKey GUARDED_BY(cs_wallet)
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:762
std::optional< OutputType > m_default_change_type
Default output type for change outputs.
Definition: wallet.h:636
int64_t nOrderPosNext GUARDED_BY(cs_wallet)=0
std::unique_ptr< WalletDatabase > const m_database
Internal database handle.
Definition: wallet.h:319
bool BackupWallet(const std::string &strDest) const
Definition: wallet.cpp:3182
std::unique_ptr< interfaces::Handler > m_chain_notifications_handler
Registered interfaces::Chain::Notifications handler.
Definition: wallet.h:414
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:338
std::string m_name
Wallet name: relative directory name or "" for default wallet.
Definition: wallet.h:316
double ScanningProgress() const
Definition: wallet.h:469
std::vector< std::string > GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2715
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:477
std::vector< WalletDescriptor > GetWalletDescriptors(const CScript &script) const
Get the wallet descriptors for a script.
Definition: wallet.cpp:3346
std::atomic< bool > m_attaching_chain
Definition: wallet.h:244
bool fBroadcastTransactions
Whether this wallet will submit newly created transactions to the node's mempool and prompt rebroadca...
Definition: wallet.h:256
int GetTxBlocksToMaturity(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3214
bool HasEncryptionKeys() const override
Definition: wallet.cpp:3395
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:2767
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet)
Definition: wallet.h:712
std::optional< bool > IsInternalScriptPubKeyMan(ScriptPubKeyMan *spk_man) const
Returns whether the provided ScriptPubKeyMan is internal.
Definition: wallet.cpp:3553
std::atomic< int64_t > m_scanning_start
Definition: wallet.h:245
TxItems wtxOrdered
Definition: wallet.h:399
uint64_t nAccountingEntryNumber
Definition: wallet.h:402
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we support the named feature
Definition: wallet.h:445
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:606
MasterKeyMap mapMasterKeys
Definition: wallet.h:369
unsigned int m_confirm_target
Definition: wallet.h:603
CFeeRate m_consolidate_feerate
When the actual feerate is less than the consolidate feerate, we will tend to make transactions which...
Definition: wallet.h:625
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:824
int64_t nRelockTime GUARDED_BY(cs_wallet)
Holds a timestamp at which point the wallet is scheduled (externally) to be relocked....
Definition: wallet.h:483
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, const CCoinControl *coin_control=nullptr) const
Definition: wallet.h:589
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
void AbortRescan()
Definition: wallet.h:465
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:745
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:667
Mutex m_unlock_mutex
Definition: wallet.h:483
void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Remove specified ScriptPubKeyMan from set of active SPK managers.
Definition: wallet.cpp:3514
bool UpgradeWallet(int version, bilingual_str &error)
Upgrade the wallet.
Definition: wallet.cpp:3137
std::atomic< uint64_t > m_wallet_flags
WalletFlags set on this wallet.
Definition: wallet.h:299
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:313
CFeeRate m_fallback_fee
If fee estimation does not have enough data to provide estimates, use this fee instead.
Definition: wallet.h:615
bool Unlock(const CKeyingMaterial &vMasterKeyIn, bool accept_no_keys=false)
Definition: wallet.cpp:3262
bool IsLocked() const override
Definition: wallet.cpp:3239
boost::signals2::signal< void(const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:742
std::map< unsigned int, CMasterKey > MasterKeyMap
Definition: wallet.h:368
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:751
std::set< ScriptPubKeyMan * > GetAllScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans.
Definition: wallet.cpp:3291
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:2628
TxSpends mapTxSpends GUARDED_BY(cs_wallet)
bool IsTxInMainChain(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:430
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
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:3577
bool IsAbortingRescan() const
Definition: wallet.h:466
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:876
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:3300
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2545
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:869
bool m_allow_fallback_fee
will be false if -fallbackfee=0
Definition: wallet.h:608
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:356
bool IsAddressUsed(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2700
void ConnectScriptPubKeyManNotifiers()
Connect the signals from ScriptPubKeyMans to the signals in CWallet.
Definition: wallet.cpp:3400
CFeeRate m_min_fee
Override with -mintxfee.
Definition: wallet.h:609
std::atomic< int64_t > m_best_block_time
Definition: wallet.h:258
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:3376
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:3010
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:3370
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:398
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:757
void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Create new DescriptorScriptPubKeyMans and add them to the wallet.
Definition: wallet.cpp:3419
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:342
std::unordered_map< uint256, CWalletTx, SaltedTxidHasher > mapWallet GUARDED_BY(cs_wallet)
Map from txid to CWalletTx for all transactions this wallet is interested in, including received and ...
int64_t nNextResend
The next scheduled rebroadcast of wallet transactions.
Definition: wallet.h:253
std::atomic< bool > fScanningWallet
Definition: wallet.h:243
std::set< ScriptPubKeyMan * > GetScriptPubKeyMans(const CScript &script) const
Get all the ScriptPubKeyMans for a script.
Definition: wallet.cpp:3310
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:417
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:138
A wrapper to reserve an address from a wallet.
Definition: wallet.h:165
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:168
CTxDestination address
The destination.
Definition: wallet.h:175
ReserveDestination & operator=(const ReserveDestination &)=delete
bool fInternal
Whether this is from the internal (change output) keypool.
Definition: wallet.h:177
~ReserveDestination()
Destructor. If a key has been reserved and not KeepKey'ed, it will be returned to the keypool.
Definition: wallet.h:189
ReserveDestination(CWallet *pwallet, OutputType type)
Construct a ReserveDestination object. This does NOT reserve an address yet.
Definition: wallet.h:181
ScriptPubKeyMan * m_spk_man
The ScriptPubKeyMan to reserve from. Based on type when GetReservedDestination is called.
Definition: wallet.h:170
int64_t nIndex
The index of the address's key in the keypool.
Definition: wallet.h:173
OutputType const type
Definition: wallet.h:171
ReserveDestination(const ReserveDestination &)=delete
Access to the wallet database.
Definition: walletdb.h:184
An instance of this class represents one database.
Definition: db.h:106
Descriptor with some wallet metadata.
Definition: walletutil.h:77
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:930
std::function< Clock::time_point()> NowFn
Definition: wallet.h:933
bool isReserved() const
Definition: wallet.h:952
std::chrono::steady_clock Clock
Definition: wallet.h:932
WalletRescanReserver(CWallet &w)
Definition: wallet.h:938
Clock::time_point now() const
Definition: wallet.h:957
void setNow(NowFn now)
Definition: wallet.h:959
TransactionError
Definition: error.h:22
FeeEstimateMode
Definition: feerate.h:21
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:2390
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:2338
bool UnlockCoin(const COutPoint &output, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2505
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::string &strPurpose)
Definition: wallet.cpp:2255
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2327
void KeepDestination()
Keep the address. Do not return it's key to the keypool when this object goes out of scope.
Definition: wallet.cpp:2463
bool IsLockedCoin(const COutPoint &output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2527
bool SignTransaction(CMutableTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Fetch the inputs and sign with SIGHASH_ALL.
Definition: wallet.cpp:1970
DBErrors LoadWallet()
Definition: wallet.cpp:2201
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:2429
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:2413
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:2275
void ReturnDestination()
Return reserved address.
Definition: wallet.cpp:2472
util::Result< CTxDestination > GetNewDestination(const OutputType type, const std::string label)
Definition: wallet.cpp:2348
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2310
bool LockCoin(const COutPoint &output, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2495
std::optional< int64_t > GetOldestKeyPoolTime() const
Definition: wallet.cpp:2376
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Definition: wallet.cpp:2085
void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string >> orderForm)
Submit the transaction to the node's mempool and then relay to peers.
Definition: wallet.cpp:2160
bool DisplayAddress(const CTxDestination &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Display address on an external signer.
Definition: wallet.cpp:2481
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2224
OutputType TransactionChangeType(const std::optional< OutputType > &change_type, const std::vector< CRecipient > &vecSend) const
Definition: wallet.cpp:2097
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2533
bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2515
util::Result< CTxDestination > GetNewChangeDestination(const OutputType type)
Definition: wallet.cpp:2365
void ForEachAddrBookEntry(const ListAddrBookFunc &func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2404
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:2281
util::Result< CTxDestination > GetReservedDestination(bool internal)
Reserve an address.
Definition: wallet.cpp:2443
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:2004
bool IsSpentKey(const CScript &scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:919
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:1280
bool LoadToWallet(const uint256 &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1048
int64_t IncOrderPosNext(WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Increment the next transaction order id.
Definition: wallet.cpp:847
void MarkInputsDirty(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed.
Definition: wallet.cpp:1165
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:579
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr) override
signify that a particular wallet feature is now used.
Definition: wallet.cpp:540
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:483
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:602
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:1647
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:1230
void updatedBlockTip() override
Definition: wallet.cpp:1367
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1158
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1617
void Flush()
Flush wallet (bitdb flush)
Definition: wallet.cpp:592
void blockDisconnected(const interfaces::BlockInfo &block) override
Definition: wallet.cpp:1351
bool IsWalletFlagSet(uint64_t flag) const override
check if a certain wallet flag is set
Definition: wallet.cpp:1499
bool AddWalletFlags(uint64_t flags)
overwrite all flags by the given uint64_t returns false if unknown, non-tolerable flags are present
Definition: wallet.cpp:1516
void blockConnected(const interfaces::BlockInfo &block) override
Definition: wallet.cpp:1338
void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
Definition: wallet.cpp:1301
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:556
void UnsetWalletFlagWithDB(WalletBatch &batch, uint64_t flag)
Unsets a wallet flag and saves it to disk.
Definition: wallet.cpp:1486
bool DummySignInput(const SigningProvider &provider, CTxIn &tx_in, const CTxOut &txout, const CCoinControl *coin_control)
Definition: wallet.cpp:1530
void ResendWalletTransactions()
Definition: wallet.cpp:1919
bool IsSpent(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Outpoint is spent if any non-conflicted transaction spends it:
Definition: wallet.cpp:645
void UnsetBlankWalletFlag(WalletBatch &batch) override
Unset the blank wallet flag and saves it to disk.
Definition: wallet.cpp:1494
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:900
bool CanGetAddresses(bool internal=false) const
Definition: wallet.cpp:1459
void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence) override
Definition: wallet.cpp:1291
void MarkDirty()
Definition: wallet.cpp:859
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:1722
bool LoadWalletFlags(uint64_t flags)
Loads the flags into the wallet.
Definition: wallet.cpp:1504
std::set< uint256 > GetTxConflicts(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1900
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
Definition: wallet.cpp:430
bool IsHDEnabled() const
Definition: wallet.cpp:1448
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:1637
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1480
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1175
void chainStateFlushed(const CBlockLocator &loc) override
Definition: wallet.cpp:529
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:1384
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:688
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:950
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:662
bool MarkReplaced(const uint256 &originalHash, const uint256 &newHash)
Mark a transaction as replaced by another transaction (e.g., BIP 125).
Definition: wallet.cpp:868
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1627
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1678
isminetype IsMine(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1406
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1431
DBErrors ReorderTransactions()
Definition: wallet.cpp:790
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:1092
void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade DescriptorCaches.
Definition: wallet.cpp:445
const CWalletTx * GetWalletTx(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:421
void Close()
Close wallet database.
Definition: wallet.cpp:597
bool FillInputToWeight(CTxIn &txin, int64_t target_weight)
Definition: wallet.cpp:1546
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:1870
void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1842
@ SIGHASH_DEFAULT
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:33
#define LogPrintf(...)
Definition: logging.h:205
SigningResult
Definition: message.h:43
Definition: node.h:39
static constexpr size_t DUMMY_NESTED_P2WPKH_INPUT_SIZE
Pre-calculated constants for input size estimation in virtual size
Definition: wallet.h:116
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:207
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:46
constexpr CAmount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:95
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:265
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:79
void MaybeResendWalletTxs(WalletContext &context)
Called periodically by the schedule thread.
Definition: wallet.cpp:1957
std::variant< TxStateConfirmed, TxStateInMempool, TxStateInactive > SyncTxState
Subset of states transaction sync logic is implemented to handle.
Definition: transaction.h:69
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:146
constexpr CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:110
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:111
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:62
static const CAmount DEFAULT_DISCARD_FEE
-discardfee default
Definition: wallet.h:81
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:58
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:69
static const bool DEFAULT_WALLETCROSSCHAIN
Definition: wallet.h:108
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:168
std::underlying_type< isminetype >::type isminefilter
used for bitflags of isminetype
Definition: wallet.h:41
static const CAmount DEFAULT_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:83
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:105
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:112
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:123
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2743
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:175
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:114
constexpr CAmount DEFAULT_PAY_TX_FEE
-paytxfee default
Definition: wallet.h:77
static const bool DEFAULT_DISABLE_WALLET
Definition: wallet.h:107
static const std::map< std::string, WalletFlags > WALLET_FLAG_MAP
Definition: wallet.h:137
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 unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:103
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: ismine.h:41
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:106
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:383
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:108
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:97
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:16
@ FEATURE_BASE
Definition: walletutil.h:17
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:125
static const CAmount DEFAULT_CONSOLIDATE_FEERATE
-consolidatefeerate default
Definition: wallet.h:85
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:278
bool IsFeatureSupported(int wallet_version, int feature_version)
Definition: walletutil.cpp:33
@ WALLET_FLAG_EXTERNAL_SIGNER
Indicates that the wallet needs an external signer.
Definition: walletutil.h:69
@ WALLET_FLAG_LAST_HARDENED_XPUB_CACHED
Definition: walletutil.h:48
@ WALLET_FLAG_KEY_ORIGIN_METADATA
Definition: walletutil.h:45
@ WALLET_FLAG_AVOID_REUSE
Definition: walletutil.h:42
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:66
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:51
@ WALLET_FLAG_BLANK_WALLET
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses,...
Definition: walletutil.h:63
static constexpr uint64_t MUTABLE_WALLET_FLAGS
Definition: wallet.h:134
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:50
std::shared_ptr< CWallet > GetWallet(WalletContext &context, const std::string &name)
Definition: wallet.cpp:159
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:99
std::variant< TxStateConfirmed, TxStateInMempool, TxStateConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:66
static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
Default for -walletrejectlongchains.
Definition: wallet.h:101
DatabaseStatus
Definition: db.h:219
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:120
std::shared_ptr< CWallet > GetDefaultWallet(WalletContext &context, size_t &count)
Definition: wallet.cpp:152
WalletContext context
ArgsManager args
OutputType
Definition: outputtype.h:17
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:414
const char * name
Definition: rest.cpp:46
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:59
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:149
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:115
A mutable version of CTransaction.
Definition: transaction.h:373
A version of CTransaction with the PSBT format.
Definition: psbt.h:952
Bilingual messages:
Definition: translation.h:18
CAmount nAmount
Definition: wallet.h:227
bool fSubtractFeeFromAmount
Definition: wallet.h:228
CScript scriptPubKey
Definition: wallet.h:226
std::optional< int > last_scanned_height
Definition: wallet.h:530
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:529
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:536
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:35
#define LOCK(cs)
Definition: sync.h:261
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
static int count
Definition: tests.c:33
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:107
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:349
ChangeType
General change type (added, updated, removed).
Definition: ui_change_type.h:9
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
std::shared_ptr< CWallet > m_wallet
Definition: interfaces.cpp:521
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:47